- What is linear search and how it works
- How to implement linear search in C
- How to handle both found and not found cases
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to perform linear search in an array.
Linear search is the simplest searching algorithm. It works by checking each element of the array one by one from the beginning until the target element is found or the end of the array is reached.
Linear search is used in many real-world applications, such as:
- Finding a contact in an unsorted phonebook
- Searching for a product in a list
- Finding a student record by roll number
- Checking if a value exists in a dataset
💡 Key Point: Linear search works on both sorted and unsorted arrays. It is simple to implement but can be slow for large arrays.
C Program for Linear Search in Array
#include <stdio.h>
int main() {
int n, i, search;
int found = 0; // Flag to track if element is found
// Ask user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare array
int arr[n];
// Read elements into the array
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Get element to search
printf("\nEnter the element to search: ");
scanf("%d", &search);
// Linear search
for(i = 0; i < n; i++) {
if(arr[i] == search) {
printf("\nElement %d found at position %d (index %d)\n",
search, i + 1, i);
found = 1;
break; // Exit loop after finding first occurrence
}
}
// If element not found
if(found == 0) {
printf("\nElement %d not found in the array.\n", search);
}
return 0;
}
Sample Output
Enter the number of elements: 6 Enter 6 elements: 10 20 30 40 50 60 Enter the element to search: 40 Element 40 found at position 4 (index 3)
When Element is Not Found:
Enter the number of elements: 5 Enter 5 elements: 10 20 30 40 50 Enter the element to search: 100 Element 100 not found in the array.
Example with Duplicate Elements:
Enter the number of elements: 7 Enter 7 elements: 10 20 10 30 10 40 50 Enter the element to search: 10 Element 10 found at position 1 (index 0)
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int n;— number of elementsint i;— loop counterint search;— element to search forint found = 0;— flag (0 = not found, 1 = found)
- Get User Input: Reads the array elements from the user.
- Get Search Element: Asks the user for the element to search.
- Linear Search:
- The
forloop iterates through each element - If
arr[i] == search, the element is found - Prints the position and index
- Sets
found = 1and breaks out of the loop
- The
- Handle Not Found: If
found == 0, prints "Element not found". - Return:
return 0;indicates successful program execution.
📝 Note: Linear search finds the first occurrence of the element. If there are duplicates, it returns the first match.
Linear Search Algorithm
Step-by-step algorithm:
- Start
- Read the array elements
- Read the element to search (target)
- Set
found = 0 - For
i = 0ton-1:- If
arr[i] == target:- Print "Element found at position i+1"
- Set
found = 1 - Break the loop
- If
- If
found == 0:- Print "Element not found"
- End
Visual Example
Searching for 40 in the array [10, 20, 30, 40, 50]:
Step 1: Check arr[0] = 10 → Not equal to 40
Step 2: Check arr[1] = 20 → Not equal to 40
Step 3: Check arr[2] = 30 → Not equal to 40
Step 4: Check arr[3] = 40 → Match found!
Result: Element found at position 4 (index 3)
Linear Search Using Function
Here's a version using a separate function for better code organization:
#include <stdio.h>
int linearSearch(int arr[], int n, int search) {
for(int i = 0; i < n; i++) {
if(arr[i] == search) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int n, search, result;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\nEnter the element to search: ");
scanf("%d", &search);
result = linearSearch(arr, n, search);
if(result != -1) {
printf("\nElement %d found at position %d (index %d)\n",
search, result + 1, result);
} else {
printf("\nElement %d not found in the array.\n", search);
}
return 0;
}
Time and Space Complexity
| Scenario | Time Complexity |
|---|---|
| Best Case (Element at first position) | O(1) |
| Worst Case (Element at last position or not found) | O(n) |
| Average Case | O(n) |
| Space Complexity | O(1) |
💻 Practice Exercise
Challenge 1: Modify the program to find all occurrences of the search element and print their positions.
Challenge 2: Count the number of occurrences of the search element in the array.
🔍 Click to Show Solution for Challenge 2
#include <stdio.h>
int main() {
int n, i, search;
int count = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\nEnter the element to search: ");
scanf("%d", &search);
// Count occurrences
for(i = 0; i < n; i++) {
if(arr[i] == search) {
count++;
}
}
if(count > 0) {
printf("\nElement %d found %d time(s) in the array.\n", search, count);
} else {
printf("\nElement %d not found in the array.\n", search);
}
return 0;
}
Frequently Asked Questions
1. What is linear search in C?
Linear search is a simple searching algorithm that checks each element of an array one by one from the beginning until the target element is found or the end of the array is reached.
2. What is the time complexity of linear search?
The time complexity is O(n) in the worst case and O(1) in the best case (when the element is at the first position).
3. When should I use linear search?
Use linear search when the array is small or unsorted. For large sorted arrays, use binary search for better efficiency.
4. Can linear search be used on a sorted array?
Yes, linear search works on both sorted and unsorted arrays. However, binary search is more efficient for sorted arrays.
5. What is the difference between linear and binary search?
Linear search checks elements one by one and works on any array. Binary search is faster but requires a sorted array. Binary search has O(log n) time complexity compared to O(n) for linear search.
💡 Tip: Linear search is the simplest searching algorithm. It's a great starting point for learning about searching algorithms.