C Programming Tutorial

Advertisements

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



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

              for(i=0;i<10;i++)
              {
                 cout<<"Enter any number : "; 
                 cin>>arr[i]; 
              }

              cout<<"\nEnter any number for search : "; 
              cin>>num; 
              
              for(i=1;i<=10;i++)
              {
                     if(num == arr[i])
                     {
                           pos=i;
                           break;
                     }                     
              }
              
              if(pos==-1)
                     cout<<"\nNo match found.";
              else
                     cout<<"\nMatch found at "<<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