Searching an array for a value is the most common occurrence in programming as well as in real life. Often it is required to search a name in a list of names or search a roll number in a list of roll numbers.
This may be carried out by comparing the value of each element of a given array with the key, i.e., which is the value we wish to search for. This is called sequential search. This method is used when the array is not an ordered array. In case of ordered arrays, the method of binary search is much more efficient. The sequential search method as illustrated in Program will search for the first occurrence of the value.
Illustrates sequential search of a value in an array
#include<stdio.h> int main() { int i; int Array[ ] = {50,12,13,15, 4,40 ,60, 30,85,40}; int key ; // key is number to be searched int Size = sizeof(Array) / sizeof(int); clrscr(); printf("Enter the number to be searched:"); scanf("%d", &key); for( i =0; i< Size; i++) if( Array[i]== key) { printf("Yes, it is in Array. Array[%d]=%d\n", i, Array[i]); goto End; } printf("The number is not in Array.\n"); End: return 0; }The output is given below. In this case the number is contained in the list
Program searches out all the elements which match the key value. If the value is not contained in the array then the program displays an appropriate message.
Illustrates searching multiple occurrences of a value
#include<stdio.h> int main() { int i; int Array[] = {25,35,40,45, 50,40 ,34, 60,94, 40}; int key; // key is number to be searched int Size = sizeof (Array) / sizeof(int); clrscr(); printf("Enter the number to be searched:"); scanf("%d", &key); for( i=0; i< Size;i++) { if( Array[i]== key ) { printf("Yes, it is in Array. Array[%d] =%d\n",i, Array[i]); } if (i == Size-1 && (Array[i]!=key) ) { printf("The number is not in the list.\n"); } } return 0 ; }