The Program in C to sort all the elements of a 4×4 matrix inputted by user is given below:
#include <stdio.h>
void sortMatrix(int matrix[4][4], int rows, int cols) {
int temp;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
for (int k = 0; k < rows; k++) {
for (int l = 0; l < cols; l++) {
if (matrix[i][j] < matrix[k][l]) {
temp = matrix[i][j];
matrix[i][j] = matrix[k][l];
matrix[k][l] = temp;
}
}
}
}
}
}
int main() {
int matrix[4][4];
printf("Enter the elements of the 4x4 matrix: \n");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
scanf("%d", &matrix[i][j]);
}
}
sortMatrix(matrix, 4, 4);
printf("Sorted matrix: \n");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the elements of the 4×4 matrix:
3
4
9
4
2
5
7
8
9
1
3
4
6
7
8
9
Sorted matrix:
1 2 3 3
4 4 4 5
6 7 7 8
8 9 9 9
Pro-Tips💡
This program uses a nested for loop to iterate through all the elements of the matrix and compares them with each other to sort them in ascending order.
The outermost for loop is used to iterate through the rows and the innermost for loop is used to iterate through the columns.
The sortMatrix function takes the matrix, number of rows and number of columns as input arguments.
This is a simple solution, however it is not very efficient as it has a O(n^2) time complexity.
A more efficient sorting algorithm such as Quicksort or Mergesort should be used if the matrix is large and contains many elements.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.