This program performs a linear search on a 1-D array to find a given element and reports its position.
C Program
#include <stdio.h>
int main() {
int arr[100], n, key, i, found = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter element to search: ");
scanf("%d", &key);
for (i = 0; i < n; i++) {
if (arr[i] == key) {
printf("Element %d found at position %d.\n", key, i + 1);
found = 1;
break;
}
}
if (!found) {
printf("Element %d not found in the array.\n", key);
}
return 0;
}
Explanation
- The array elements are read one by one into
arr. - A single
forloop scans each element and compares it withkeyusing==. - When a match is found, the 1-based position is printed and the
foundflag is set so the "not found" message is skipped;breakstops the search immediately. - If the loop completes without a match,
foundstays 0 and the "not found" message prints.
Sample Output
Enter number of elements: 5
Enter 5 elements:
12 45 7 23 9
Enter element to search: 23
Element 23 found at position 4.
Enter number of elements: 3
Enter 3 elements:
1 2 3
Enter element to search: 9
Element 9 not found in the array.