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