Write a C program to search an element in an array

Description: Take an array of 5 numbers and a number to search. Print its position, or a message if it is not found.

Hint:

  • Compare the number with every element one by one. Stop when it is found.

C program for linear search

#include <stdio.h>

int main(void) {
    int a[5] = {12, 45, 7, 67, 30};
    int key, found = -1;

    printf("Enter the number to search: ");
    scanf("%d", &key);

    for (int i = 0; i < 5; i++) {
        if (a[i] == key) {
            found = i;
            break;
        }
    }

    if (found != -1) {
        printf("%d found at index %d\n", key, found);
    } else {
        printf("%d not found\n", key);
    }
    return 0;
}

Output:

Output of the above program is

Enter the number to search: 67
67 found at index 3

How it works

  • found starts as -1, which means “not found”.
  • When the value matches, we save the index in found and stop the loop with break.
  • Index 3 is the fourth element, because indexes start from 0.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.