Search an element in 2D matrix
C program to search an element in 2D matrix.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void search(int mat[MAX][MAX], int row, int col, int num)
{
int i, j, flag;
flag = 0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(mat[i][j] == num)
{
printf("\nElement found at position (%d,%d)",i,j);
flag = 1;
}
}
}
if(flag == 0)
{
printf("\nElement not found");
}
}
void main()
{
int mat[MAX][MAX];
int row, col, num;
printf("Enter the number of rows\t:");
scanf("%d",&row);
printf("Enter the number of columns\t:");
scanf("%d",&col);
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("Enter the number to be searched\t:");
scanf("%d",&num);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
search(mat, row, col, num);
getch();
}
Output
********** Run1 **********
Enter the number of rows :3
Enter the number of columns :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [1][0] :5
Element [1][1] :5
Element [1][2] :6
Element [1][3] :7
Element [2][0] :8
Element [2][1] :9
Element [2][2] :10
Element [2][3] :5
Enter the number to be searched :5
Matrix entered is
1 2 3 4
5 5 6 7
8 9 10 5
Element found at position (1,0)
Element found at position (1,1)
Element found at position (2,3)
********** Run2 **********
Enter the number of rows :3
Enter the number of columns :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [1][0] :4
Element [1][1] :3
Element [1][2] :2
Element [1][3] :1
Element [2][0] :1
Element [2][1] :2
Element [2][2] :2
Element [2][3] :3
Enter the number to be searched :5
Matrix entered is
1 2 3 4
4 3 2 1
1 2 2 3
Element not found