Linear Search: C

In this video tutorial we shall see how we can search for a number in an array in linear fashion.

First ask the user to enter the number to be searched. Store it inside a variable called key.
Now start comparing key value with a[i] using a for loop. If the key is found in the array, then assign 1 to flag orelse flag will be 0.

Depending upon the value of flag, print the message.

If flag is 1, search is successful.
If flag is 0, search failed. in the sense, the number is not present in the given array.

Video Tutorial: Linear Search: C



YouTube Link: https://www.youtube.com/watch?v=AqjVd6FVFbE [Watch the Video In Full Screen.]



Full Source Code

#include < stdio.h >
#include < conio.h >

void main()
{
 int a[20], key, N, flag = 0, i;
 clrscr();

 printf("Enter array limit\n");
 scanf("%d", &N);

 printf("Enter %d elements\n", N);
 for(i=0; i < N; i++)
  scanf("%d",&a[i]);

 printf("Enter the number to be searched\n");
 scanf("%d", &key);

 for( i=0; i < N; i++)
  if( a[i] == key )
  {
  flag = 1;
  break;
  }

 if(flag)
  printf("\nSearch Successful\n");
 else
  printf("\nSearch Failed\n");
 getch();
}

Output
Enter array limit
5
Enter 5 elements
77
0
13
9
55
Enter the number to be searched
9
Search Successful