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

        
Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 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 Best Website and Software Company in Allahabad