Linear Search: C

Advertisement:

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


You need to a flashplayer enabled browser to view this YouTube video

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



Full Source Code

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
29
30
31
#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

Leave a Reply

Your email address will not be published. Required fields are marked *