Programming Examples

Cpp program to search an element in an array


Write a cpp program to search an element in an array

Solution

#include<iostream>
using namespace std;
int main(){
    int arr[50],item,i,size,flag=0;
    cout<<"Enter the desired array size";
    cin>>size;
    cout<<"Enter the elements";
    for(i=0;i<size;i++)
    {
        cin>>arr[i];
    }
    cout<<"Enter the element to be searched for :";
    cin>>item;
    for(i=0;i<size;i++)
    {
        if(arr[i]==item)
        {
            flag=1;
            break;
        }
    }
    if(flag==1)
    {
        cout<<"Element found at index "<<i<<", position "<<i+1<<endl;
    }
    else
    {
        cout<<" Element cannot be found"<<endl;
    }
    return 0;
}
Output

Enter the desired array size 6

Enter the elements   

12

13

45

1

34

23

Enter the element to be searched for : 1

Element found at index 3, position 4

        
Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz