C Program to Search an Element in an Array Using Linear or Sequential Search

Before making the C program to search an element in an array using linear search, first understand what linear search means. Sequential search or Linear search is performed in linear way i.e. it starts from the beginning of the list and continues till we find the item or reach the end of list. The item to be searched is compared with each element of the list one by one, starting from the first element.

Let’s See The Program ►►


//Function Prototype Declaration
int linearSearch(int [],int,int);
void main()
   int size,arr[100],item,index;

   printf("Enter the Size of the Array : ");

   printf("\nEnter the elements of the Array : ");
   for(int i=0;i<size;i++) {
   printf("\nArray[%d] = ",i+1);

   printf("\nEnter the Item to be searched : ");

   index=linearSearch(arr,size,item); //Function Call

   printf("\n%d not found in the Array... Existing...",item);

   printf("\n%d found at position %d ",item,++index);

 //Function Definition
int linearSearch(int arr[],int size,int item)
int i=0;

while(i<size && item!=arr[i])

             return i;

             return -1;

Explanation ►► I created a function name linearSearch that will return a value of type int and will receive base address of array, array size, and the item to be searched as its parameter at the time of the call of function. Then in function I conditioned the while loop to execute until the value of i is less than size of the array (i<size) or until the value in the array does not match with the item to be searched (item!=arr[i]). As the item will match the while loop will terminate and the value of the i at that time will be return by the function following by the if statement, if otherwise not found the item in the array then the loop will execute to its end, means until the value of i is less than the size of the array and in this case the value -1 will be return by the function following the else statement. I return this value to make sure that the item is found or not as we know the value of index (or say i in the program) will never be -1.


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 )

Google+ photo

You are commenting using your Google+ 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