In this tutorial we shall try to make a program for Linear Search.Linear Search is the basic and easiest searching method and is for junior programmers.The steps involved in searching a number using Linear Search algorithm is:
Method
1.Get the data from the user and store it in an array.
2.Ask the user to enter the number which he interested to search.
3.Make a for loop such that,in it compare each element of the array with the key given by the user.
4.If the element is found…..Display the appropriate the message to the user.
5.If the element is not found…..display the appropriate the message to the user.
Now the code is as follows:
#include<stdio.h> #include<conio.h> void main() { int data[50],size,i,key,flag=0; clrscr(); printf("\nEnter the Array Size:"); //Get the size of the array going to be entered scanf("%d",&size); printf("\nEnter the Array Elements:"); //Enter those number of elements in to the array for(i=0;i<size;i++) scanf("%d",&data[i]); printf("\nEnter the Key:"); //Enter the key to search in array scanf("%d",&key); for(i=0;i<size;i++) //In this for loop we are going to compare each element with key { if(data[i]==key) flag++; } if(flag!=0) printf("\nkey found in the given data",i); else printf("\nKey not found in the given data"); getch(); }
OUTPUT:
YOu can download the program:download
IF you have any doubts you can comment them.