Find the Maximum Element in a Matrix
Find the largest integer present in a given R×C matrix by examining all elements
Understand the Problem
Problem Statement
You are given a matrix of size R×C containing integers. Write a program to find the maximum element present in the matrix.
Note: Make sure to read the input matrix correctly and find the maximum element in the matrix as specified in the question.
Constraints
- 2 ≤ R, C ≤ 50
- 1 ≤ Each integer value in the matrix ≤ 1000
- The matrix will contain at least 4 elements (minimum 2×2)
Examples
3 4
5 10 25 8
12 9 7 6
11 14 18 2225The matrix contains elements [5,10,25,8,12,9,7,6,11,14,18,22]. The largest element among all these values is 25, which is located in the first row, third column.
4 3
30 40 5
16 28 35
55 90 15
10 25 6090The matrix contains elements [30,40,5,16,28,35,55,90,15,10,25,60]. The largest element among all these values is 90, which is located in the third row, second column.
Solution
#include <stdio.h>
int main() {
int R, C;
scanf("%d %d", &R, &C);
// Initialize matrix with fixed size (constraints say max 50x50)
int matrix[50][50];
// Read matrix elements
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Initialize max_element with first element
int max_element = matrix[0][0];
// Find maximum element by iterating through all elements
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (matrix[i][j] > max_element) {
max_element = matrix[i][j];
}
}
}
// Output the result
printf("%d\n", max_element);
return 0;
}This C solution starts by reading the matrix dimensions R and C. It then declares a fixed-size 2D array (50×50) based on the problem constraints and reads all matrix elements using nested loops.
The algorithm initializes max_element with the first element of the matrix. Then it uses nested loops to traverse every element in the matrix. For each element, it compares the current value with max_element and updates max_element if a larger value is found.
After examining all elements, it prints the maximum value. The solution uses standard C input/output functions and follows the typical pattern for matrix traversal in C.