C++ program to search a given element in an array
The below program simply takes all the inputs from the user and prints "PRESENT" if the element is found in the array and prints "ABSENT" if the element is not found in the array.
This code is a simple execution of "The Linear Search Algorithm" in C++.
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
for(int i=0;i<n;i++){ //searching the element via loop
if(a[i]==s){ //if found update flag to 1
flag=1;
}
}
if(flag==1){ //element found print PRESENT
cout<<"PRESENT";
}
else{ //element not found print ABSENT
cout<<"ABSENT";
}
return 0;
}
Input
5
1 2 3 4 5
Output
Enter an element to search
3
PRESENT
Input
5
1 2 3 4 5
Output
Enter an element to search
6
ABSENT
0 Comments