C Program to search an element in an array.
Objective
Write a C program to search for a specific element in an array.
Algorithm / Approach
- Read 5 elements into an array.
- Prompt the user for a number to
searchfor. - Initialize a
flag = 0. - Loop through the array. If
a[i] == search, setflag = 1, print the index, and usebreakto stop searching. - After the loop, if
flag == 0, print "Not Found".
main.c
#include<stdio.h>
int main( ) {
int i,search,flag = 0;
int a[5];
printf("Enter 5 elements : ");
for(i=0; i < 5; i++) {
scanf("%d",&a[i]);
}
printf("Enter no. to search : ");
scanf("%d",&search);
for(i=0; i < 5; i++) {
if( a[i] == search ) {
flag = 1;
break;
}
}
if(flag == 1) {
printf("Fount at %d", (i+1));
}
else {
printf("Not Fount");
}
return 0;
}
Expected Output
Enter 5 elements : 10 12 15 23 20 Enter no.to search : 15 Found at 3
Explanation of the Program
- This is the Linear Search algorithm. It checks every single box in the array one by one until it finds a match.
- The
flagvariable acts as a memory trigger. Because the loop will naturally exit whether it finds the number or not, we check the flag after the loop to know if the search was successful.
Complexity
Time Complexity
O(n) - In the worst case, it checks every element.
Space Complexity
O(n)