Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to search an element in an array.

C Code Example — Array Programs

ADVERTISEMENT

C Program to search an element in an array.

Objective

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

Algorithm / Approach

  1. Read 5 elements into an array.
  2. Prompt the user for a number to search for.
  3. Initialize a flag = 0.
  4. Loop through the array. If a[i] == search, set flag = 1, print the index, and use break to stop searching.
  5. After the loop, if flag == 0, print "Not Found".
main.c
#include<stdio.h>
int main( ) {
 int i,search,flag = 0;
 int a[5];
 printf("Enter 5 elements : ");
 for(i=0; i < 5; i++) {
  scanf("%d",&a[i]);
 }
 printf("Enter no. to search : ");
 scanf("%d",&search);
 for(i=0; i < 5; i++) {
  if( a[i] == search ) {
    flag = 1;
    break;
  }
 }
 if(flag == 1) {
  printf("Fount at %d", (i+1));
 }
 else {
  printf("Not Fount");
 }
 return 0;
}

Expected Output

Enter 5 elements : 10 12 15 23 20
Enter no.to search : 15
Found at 3

Explanation of the Program

  • This is the Linear Search algorithm. It checks every single box in the array one by one until it finds a match.
  • The flag variable acts as a memory trigger. Because the loop will naturally exit whether it finds the number or not, we check the flag after the loop to know if the search was successful.

Complexity

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