Write a program in C to search an element in a row wise and column wise sorted matrix.

Previous
Next

Solution:

  • In this code, we search for an element in the given matrix.
  • We define the array with elements directly.
  • We use nested loops to search for element using row and column index.
  • When element found, we display the intersection point of rows and columns as element location.
#include <stdio.h>
int main()
{
	int arr[4][4] = {{5, 7, 13, 6},{2, 9, 11, 17}, {6, 1, 14, 19},{3,8,12,18}};
	int i,j,ele, found=0;
	printf("Given matrix is : \n");
	for(i=0; i<4; i++)
	{
		for (j=0; j<4; j++)
		{
			printf("%d  ", arr[i][j]);
		}
		printf("\n");
	}
	printf("Enter element to search : ");
	scanf("%d", &ele);
	for(i=0; i<4; i++)
	{
		for (j=0; j<4; j++)
		{
			if(arr[i][j] == ele )
			{
printf("\Found at the position in the matrix is:  %d, %d", i, j);
				found=1;
			}
		}
	}
	if(!found)
		printf("No such element \n");
	
	return 0;
}
Previous
Next

Courses Enquiry Form