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
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?