Linear Search Program in C with Output
Search for a value in an integer array in C by checking each element in order, and print where it is found or that it is not found.
- Time
O(n) worst and average case, O(1) best case - Space
O(1) - Hints3
- Read3 min
Linear search in C loops through the array from index 0 to n - 1 and compares each element with the key. When arr[i] == key, it returns i at once. If the loop ends with no match, it returns -1, and the caller prints "not found". It works on unsorted arrays, takes O(n) time in the worst case and O(1) extra space.
Problem statement
Write a linear search program in C. Given an array and a key, find the index of the first element equal to the key. Print the index if it is found, or a "not found" message if it is not.
The array does not need to be sorted.
An integer n, then n integers, then the key to search for.
"<key> found at index <i>" or "<key> not found".
Examples
arr = {23, 8, 41, 16, 37}, key = 1616 found at index 3Index 0 is 23, 1 is 8, 2 is 41, 3 is 16.
arr = {23, 8, 41, 16, 37}, key = 5050 not foundAll five elements are compared and none equals 50.
Constraints
- 1 <= n <= 100
- Elements can be in any order and can repeat
Think before you code
Reveal the questions to ask yourself first
- Can you stop the loop as soon as you find the key?
- At what point can you be sure the key is not in the array?
- What value can you return for "not found" that can never be a real index?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Linear search algorithm
- For each index
ifrom 0 ton - 1: - If
arr[i] == key, returni. - After the loop, return
-1.
Array indexes start at 0, so -1 can never be a real position. The caller checks for
-1 to decide which message to print.
| Case | Comparisons for n elements |
|---|---|
| Best: key at index 0 | 1 |
| Worst: key last or missing | n |
| Average, key present | about n / 2 |
Two ways to write it
- Function returning an index: clean, reusable, and easy to test. This is the main solution below.
- Flag variable in main: set
found = 1andbreakwhen the key matches, then checkfoundafter the loop. Many lab manuals use this version.
If the array is sorted, binary search finds the key with far fewer comparisons. See binary search in Java for that method.
Dry run
Walk through the example step by step
arr = {23, 8, 41, 16, 37}, key = 16:
i | arr[i] | arr[i] == 16?
--+--------+--------------
0 | 23 | no
1 | 8 | no
2 | 41 | no
3 | 16 | yes, return 3
For key = 50, all five rows say "no", the loop ends, and the function returns -1.
Solution
Reveal the full C solution
#include <stdio.h>
int linear_search(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main(void) {
int arr[] = {23, 8, 41, 16, 37};
int n = sizeof(arr) / sizeof(arr[0]);
int keys[] = {16, 23, 50};
for (int k = 0; k < 3; k++) {
int index = linear_search(arr, n, keys[k]);
if (index != -1) {
printf("%d found at index %d\n", keys[k], index);
} else {
printf("%d not found\n", keys[k]);
}
}
return 0;
}Output:
16 found at index 3
23 found at index 0
50 not found
23 is found on the first comparison, the best case. 50 needs all five comparisons, the worst case.
Search element in array in C with user input
This is the flag-and-break version. It prints a 1-based position, because users count from 1.
#include <stdio.h>
int main(void) {
int n, key, arr[100];
int found = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter element to search: ");
scanf("%d", &key);
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
printf("%d found at position %d\n", key, i + 1);
found = 1;
break;
}
}
if (!found) {
printf("%d not found in the array\n", key);
}
return 0;
}
Enter number of elements: 5
Enter 5 numbers: 10 25 30 45 50
Enter element to search: 45
45 found at position 4
Enter number of elements: 5
Enter 5 numbers: 10 25 30 45 50
Enter element to search: 35
35 not found in the array
breakstops the loop after the first match, so later elements are not checked.- The "not found" message is printed once, after the loop, only when
foundis still 0.
Find all occurrences
Remove the early exit to report every index where the key appears.
#include <stdio.h>
int main(void) {
int arr[] = {4, 7, 4, 9, 4, 2};
int n = 6, key = 4, count = 0;
printf("%d found at index: ", key);
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
printf("%d ", i);
count++;
}
}
printf("\nTotal occurrences: %d\n", count);
return 0;
}
4 found at index: 0 2 4
Total occurrences: 3
This version always checks all n elements, because it cannot know whether another
match is still ahead.
The Python version is on linear search program in Python and the Java version on linear search in Java. To sort an array first, see selection sort program in C.
O(n) worst and average case, O(1) best caseO(1)Review before the interview
Common mistakes
- Writing else return -1; inside the loop, so only the first element is ever checked.
- Printing "not found" inside the loop, once for every element that does not match.
- Using = instead of == in the if condition, which assigns the key and is almost always true.
- Looping with i <= n, which reads one element past the end of the array.
- Forgetting break in the flag version, so a duplicate key prints "found" more than once.
Edge cases to test
- Key at index 0: found with one comparison.
- Key at the last index: found, but only after n comparisons.
- Duplicates: the basic version returns the first index only.
- n = 0: the loop does not run and the function returns -1.
Interview follow-ups
- How would you return the last index of the key instead of the first?
- How would you write linear search using recursion?
- What is a sentinel linear search, and how does it save one comparison per step?
Keep practising
Linear Search Program in Python with Output
Hints · Dry run · SolutionSolve Similar problemLinear Search in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemBinary Search in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemLargest Element in an Array in C
Hints · Dry run · SolutionSolve Related learningWhat Is An Array
TutorialLearn Related learningWhat Is An Algorithm
TutorialLearn Related learningC Programming Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartBuilding your programming basics?
CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.
