Search for an Element in a 2-D Array in C

This program searches for a given element in a 2-D array and displays its position (row and column) if found.

C Program

#include <stdio.h>

int main() {
    int a[10][10], m, n, i, j, key, found = 0;

    printf("Enter number of rows (m) and columns (n): ");
    scanf("%d %d", &m, &n);

    printf("Enter elements of the matrix:\n");
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);

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

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

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

    return 0;
}

Explanation

  • Nested loops scan the matrix row by row, column by column, comparing each element with key.
  • When a match is found, the 1-based row and column are printed, found is set, and break exits the inner loop — the second if (found) break; is needed to also exit the outer loop, since a single break only escapes the innermost loop in C.
  • If no match is found after scanning the whole matrix, the "not found" message prints.

Sample Output

Enter number of rows (m) and columns (n): 2 3
Enter elements of the matrix:
1 2 3
4 5 6
Enter element to search: 5
Element 5 found at row 2, column 2.

Leave a Comment