Home

A program to search an element in the matrix

C Programming Language 061

The following code shows how to write a program to search an element in the matrix. Print the row and column position if found.

Program

#include <stdio.h>

void main()
{
    int a[10][10], m, n, i, j, key, found = 0;
    printf("Enter order m,n [m x n]: ");
    scanf("%d %d", &m, &n);

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

    printf("Enter the element to be searched: ");
    scanf("%d", &key);

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

    if (found == m * n)
    {
        printf("Element not found");
    }

    printf("\n");
}

Result

Enter order m,n [m x n]: 2 3
Enter values:
1 2 3
4 5 6
Enter the element to be searched: 5
Element found at row: 2, column: 2


Last Updated on

Next Post: Rules vs Guidelines →

Comments