Linear Search Program in C

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:
l_search
YOu can download the program:download
IF you have any doubts you can comment them.

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s