WAP to search an element in an array
Objective
Write a C++ program to search for a specific element in an array.
Algorithm / Approach
- Initialize an array with values.
- Read a target number
nto search for. - Set
flag = 0. - Loop through the array. If
a[i] == n, setflag = 1,breakthe loop, and retaini. - If
flag == 0, print "Not Found", else print the position (i+1).
main.cpp
#include<iostream>
using namespace std;
int main() {
int a[5]={1,10,23,45,21};
int i,n,flag = 0;
cout<<"Enter a Element : ";
cin>>n;
for(i=0; i< 5; i++){
if(a[i]==n){
flag = 1;
break;
}
}
if(flag==0) {
cout<<"Element not Found\n";
}
else {
cout<<"Found at "<< i+1<< endl;
}
return 0;
}
Expected Output
Enter a Element : 23 Found at 3
Explanation of the Program
- This is the Linear Search algorithm. It checks every single slot in the array one by one until it finds a match.
- The
flagvariable acts as our memory. Because the loop will exit naturally whether it finds the number or not, we check the flag after the loop is over to determine if the search was successful.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)