C Exercises: Search an element in a row wise and column wise sorted matrix
C Array: Exercise-67 with Solution
Write a program in C to search for an element in a row wise and column wise sorted matrix.
Pictorial Presentation:

Sample Solution:
C Code:
#include <stdio.h>
int searchElement(int arr2D[4][4], int n, int x)
{
int i = 0, j = n-1;
while ( i < n && j >= 0 )
{
if ( arr2D[i][j] == x )
{
printf("\nThe element Found at the position in the matrix is: %d, %d", i, j);
return 1;
}
if ( arr2D[i][j] < x )
j--;
else
i++;
}
printf("\nThe given element not found in the 2D array.");
return 0;
}
int main()
{
int arr2D[4][4] = { {15, 23, 31, 39},
{18, 26, 36, 43},
{25, 28, 37, 48},
{30, 34, 39, 50},
};
int i,j,v;
v=37;
//------------- print original array ------------------
printf("The given array in matrix form is : \n");
for(i = 0; i < 4; i++)
{
for (j=0;j<4;j++)
{
printf("%d ", arr2D[i][j]);
}
printf("\n");
}
//------------------------------------------------------
printf("The given value for searching is: %d",v);
searchElement(arr2D, 4, v);
return 0;
}
Sample Output:
The given array in matrix form is : 15 23 31 39 18 26 36 43 25 28 37 48 30 34 39 50 The given value for searching is: 37 The element Found at the position in the matrix is: 2, 2
Flowchart:

C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to count the number of inversion in a given array.
Next: Write a program in C to to print next greater elements in a given unsorted array. Elements for which no greater element exist, consider next greater element as -1.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
C Programming - What is the argument for printf that formats a long?
Put an l (lowercased letter L) directly before the specifier.
unsigned long n; long m; printf("%lu %ld", n, m);
Ref : https://bit.ly/3dIwfkP
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises