Search an Element in an Array
In this example code, you will learn to Search an Element in an Array in C programming. Follow the following steps to complete the program:-
Step 1 Create an array list by input some numbers.
Step 2 Input a number to find location.
Step 3 Start a loop and check every element with search number.
Step 4 If search number matched with array element, store location in location variable.
Step 5 Print the number, and value of location variable.
Program to Search an Element in an Array in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <stdio.h> int main() { int j, k=0, loc=0, arr[5], item; clrscr(); printf("\nInput 5 Numbers : "); for(j=0; j<5;j++) { scanf("%d", &arr[j]); } printf("\nEnter the element to search in the array :"); scanf("%d", &item); while(loc==0 && k<5) { if(item==arr[k]) loc=k+1; else k++; } if(loc==0) printf("\n %d is not found in array",item); else printf("\n %d found at location of %d", item,loc); getch(); return 0; } |
Output
Enter 5 Numbers : 3 6 2 9 1
Enter the element to search in the array :2
2 found at location of 3
Check out our other C programming Examples