Advertisement
ruhan008

Linear Search program

Nov 8th, 2023 (edited)
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. // 1) WAP to implement linear search
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int main(){
  6.    
  7.     cout<<"Enter the size of the array: ";
  8.     int n;
  9.     cin>>n;
  10.     int arr[n];
  11.     cout<<"Enter the array elements: ";
  12.     for(int i=0;i<n;i++) {
  13.         cin>>arr[i];
  14.     }
  15.  
  16.     cout<<"Enter the element to be searched: ";
  17.     int element;
  18.     cin>>element;
  19.     int index=-1;
  20.     for(int i=0;i<n;i++){
  21.         if(arr[i]==element){
  22.             index=i;
  23.             break;
  24.         }
  25.     }
  26.  
  27.     if(index!=-1){
  28.         cout<<"Element found at index: "<<index<<endl;
  29.     }
  30.     else cout<<"Element not found!!!"<<endl;
  31.  
  32.    
  33.     return 0;
  34. }
  35. /*
  36.     OUTPUT:
  37.     Enter the size of the array: 5
  38.     Enter the array elements: 8 9 1 2 19
  39.     Enter the element to be searched: 2
  40.     Element found at index: 3
  41. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement