C Programming Tutorial

Advertisements

Write a program to search a number in an array using linear search in C



       #include<stdio.h>
       #include<conio.h>
       void main()
       {
              int arr[10],i,num,pos=-1; 
              clrscr();

              for(i=0;i<10;i++)
              {
                 printf("Enter any number : "); 
                 scanf("%d",&arr[i]); 
              }

              printf("\nEnter any number for search : "); 
              scanf("%d",&num); 
              
              for(i=1;i<=10;i++)
              {
                     if(num == arr[i])
                     {
                           pos=i;
                           break;
                     }                     
              }
              
              if(pos==-1)
                     printf("\nNo match found.");
              else
                     printf("\nMatch found at %d",pos);                

              getch();              
       }

   Output : 

              Enter any number : 78
              Enter any number : 45
              Enter any number : 12
              Enter any number : 89
              Enter any number : 56
              Enter any number : 23
              Enter any number : 79
              Enter any number : 46
              Enter any number : 13
              Enter any number : 82
              
              Enter any number for search : 79
              
              Match found at 6




Advertisement