Explanation
To find the greatest element in each row of a two-dimensional array
#include <stdio.h>
int main() {
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int matrix[rows][cols];
// Input elements into the 2D array
printf("Enter the elements of the 2D array:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Find the greatest element in each row and print
for (int i = 0; i < rows; i++) {
int maxElement = matrix[i][0];
for (int j = 1; j < cols; j++) {
if (matrix[i][j] > maxElement) {
maxElement = matrix[i][j];
}
}
printf("The greatest element in row %d is: %d\n", i + 1, maxElement);
}
return 0;
}
the program works:
-
It takes input for the number of rows and columns for the 2D array.
-
It initializes a 2D array named ‘ matrix ‘ with the specified dimensions.
-
It takes input for the elements of the 2D array.
-
It then iterates through each row of the matrix, finding the maximum element in each row and printing it. The ‘ maxElement ‘variable is used to keep track of the greatest element.
This program will output the greatest element in each row of the 2D array.