Linear Search in a 1-D Array in C

This program performs a linear search on a 1-D array to find a given element and reports its position.

C Program

#include <stdio.h>

int main() {
    int arr[100], n, key, i, found = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

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

    for (i = 0; i < n; i++) {
        if (arr[i] == key) {
            printf("Element %d found at position %d.\n", key, i + 1);
            found = 1;
            break;
        }
    }

    if (!found) {
        printf("Element %d not found in the array.\n", key);
    }

    return 0;
}

Explanation

  • The array elements are read one by one into arr.
  • A single for loop scans each element and compares it with key using ==.
  • When a match is found, the 1-based position is printed and the found flag is set so the "not found" message is skipped; break stops the search immediately.
  • If the loop completes without a match, found stays 0 and the "not found" message prints.

Sample Output

Enter number of elements: 5
Enter 5 elements:
12 45 7 23 9
Enter element to search: 23
Element 23 found at position 4.

Enter number of elements: 3
Enter 3 elements:
1 2 3
Enter element to search: 9
Element 9 not found in the array.

Leave a Comment