Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to search an element in an array

C++ Code Example — Array Programs

ADVERTISEMENT

WAP to search an element in an array

Objective

Write a C++ program to search for a specific element in an array.

Algorithm / Approach

  1. Initialize an array with values.
  2. Read a target number n to search for.
  3. Set flag = 0.
  4. Loop through the array. If a[i] == n, set flag = 1, break the loop, and retain i.
  5. 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 flag variable 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)
ADVERTISEMENT