C++ program to search and print index position of an element in array


C++ program to search and print index position of an element in array

        The below program is based on arrays. The user will provide array size and its elements along with the element whose index position the user wants to know.

        You need to search the element in the array if the element is found print "found at: index position". If the element is not found print "Element is not found".

        Remember the index position and actual position of an array element are different the index starts with zero and not 1.


Code

#include <iostream>

using namespace std;


int main()

{

    int n;                              //array size

    cin>>n;

    

    int a[n];                       //array declaration

    

    for(int i=0;i<n;i++){           //reading array

        cin>>a[i];

    }

    int s;

    cout<<"Enter an element to search "<<endl;

    cin>>s;

    

    int flag=0;                 //initially taking as not found

    int position;

    

    for(int i=0;i<n;i++){           //searching the element via loop

        if(a[i]==s){                //if found update flag to 1

            flag=1;

            position=i;

        }

    }

    

    if(flag==1){                    //element found print index position

        cout<<"Found at: "<<position;

    }

    else{                           //element not found 

        cout<<"Element not found";

    }


    return 0;

}


Input

5

1 2 3 4 5


Output

Enter an element to search 

5

Found at: 4

Post a Comment

0 Comments