C program to use a linear search for a number stored in a array of N numbers




In this c program we are using linear search, in c language there are so many search algorithms, most simple algorithm is linear search.

In linear search when user enters a number for searching the algorithm checks that number with all other numbers in the array until the search is found or the array is completed. the best case in linear search is the item is found first of the array. Worst is the item found last of the array.

so this c program we need to declare a array and insert all the values into the array. After inserting all elements we need the user to enter the number that needs to be searched using linear search. after assign that number in to a variable check each value of array with the variable user inputs using for loop

Finally displays output with suitable message

===================================================================
#include <stdio.h>
 
#include <conio.h>
 
void main()
 
{
 
   int array[10];
 
   int i, N, keynum, found=0;     /* declares array and variables key num found etc as integer */
 
   clrscr();
 
   printf("Enter the value of N\n");     /* enters the values by user */
 
   scanf("%d",&N);
 
   printf("Enter the elements one by one\n");    /* enter the values into a array and print the numbers */
 
   for(i=0; i<N ; i++)
 
   {
 
	scanf("%d",&array[i]);
 
   }
 
   printf("Input array is\n");
 
   for(i=0; i<N ; i++)
 
   {
 
	printf("%d\n",array[i]);
 
   }
 
   printf("Enter the element to be searched\n");  /* accepts number that needs to be searched */
 
   scanf("%d", &keynum);
 
   /* Linear search begins */
 
     for ( i=0; i < N ; i++)               /* using linear search we compare the number with other elements in array */
 
     {
 
       if( keynum == array[i] )
 
       {
 
	   found = 1;
 
	   break;
 
       }
 
    }
 
  if ( found == 1)
 
     printf("SUCCESSFUL SEARCH\n");          /* prints the result success of failure */
 
  else
 
     printf("Search is FAILED\n");
 
}	/* End of main */
==================================================================
OUTPUT of C program to input N numbers (integers or reals)
==================================================================
RUN 1
Enter the value of N
5
Enter the elements one by one
23
12
56
43
89
Input array is
23
12
56
43
89
Enter the element to be searched
56
SUCCESSFUL SEARCH

RUN 2
Enter the value of N
3
Enter the elements one by one
456
213
879
Input array is
456
213
879
Entee the element to be searched
1000
Search is FAILED