Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to search an element in Array using "Linear Search".

C Code Example — Data Structure Programs

ADVERTISEMENT

C Program to search an element in Array using "Linear Search".

Objective

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

Algorithm / Approach

  1. Initialize an array with random elements.
  2. Read the target number n to search for.
  3. Set flag = 0.
  4. Iterate through the array from index 0 to the end.
  5. If a[i] == n, set flag = 1, print the index, and break out of the loop.
  6. If the loop finishes and flag == 0, print "Not found".
main.c
#include<stdio.h>
 int main() {
 int a[10]={10,14,19,26,27,31,33,35,42,44};
 int i,n,flag=0;

 printf("Enter no. to Search: ");
 scanf("%d",&n);
 for(i=0; i<=10; i++) {
  if(a[i]==n) {
   flag=1;
   break;
  }
 }
 if(flag==1) {
  printf("%d found at %d pos",n,i);
 }
 else {
  printf("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 (or Sequential Search) is the simplest search algorithm.
  • It works exactly like searching for a specific page in a book by flipping through every single page starting from page 1. It checks every element one by one until it finds a match or runs out of elements.

Complexity

Time Complexity O(n) - In the worst case, it checks every single element.
Space Complexity O(1)
ADVERTISEMENT