Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to search an element in Array using "Linear Search".

C++ Code Example — Data Structure Programs

ADVERTISEMENT

WAP to search an element in Array using "Linear Search".

Objective

Write a C++ program to search for an element using Linear Search.

Algorithm / Approach

  1. Initialize an array with values.
  2. Read the search target n from the user.
  3. Set a flag = 0.
  4. Loop through every element of the array from index 0 to the end.
  5. If a[i] == n, set flag = 1, print the index, and break the loop.
  6. If the loop finishes and flag == 0, print "Not found".
main.cpp
#include<iostream>
 using namespace std;
 int main() {
 int a[10]={10,14,19,26,27,31,33,35,42,44};
 int i,n,flag=0;

 cout<<"Enter no. to Search: ";
 cin>>n;
 for(i=0; i<=10; i++) {
  if(a[i]==n) {
   flag=1;
   break;
  }
 }
 if(flag==1) {
  cout<< n<<" found at "<< i;
 }
 else {
  cout<<"Number not found.";
 }
 return 0;
}

Expected Output

OUTPUT : 1
Enter no. to Search: 33
33 found at 6 pos

OUTPUT : 2
Enter no. to Search: 71
Number not found.

Explanation of the Program

  • Linear Search is the simplest searching algorithm. It works exactly like looking for a book on a shelf by checking every single book from left to right.
  • It is highly effective for small or unsorted arrays, but scales poorly for massive datasets because it might have to check every single element before finding what it needs.

Complexity

Time Complexity O(n) - In the worst case, the target is at the very end of the array.
Space Complexity O(1)
ADVERTISEMENT