Home > Article > Backend Development > C program to sort all columns and rows of a matrix
Write code to sort all rows of a matrix in ascending order and all columns in descending order. The size and elements of the matrix are provided by the user at runtime.
The solution to sort all rows of a matrix in ascending order and all columns in descending order in C programming language is explained below:
For ascending order The logic for sorting rows is as follows:
for (i=0;i<m;++i){ for (j=0;j<n;++j){ for (k=(j+1);k<n;++k){ if (ma[i][j] > ma[i][k]){ a = ma[i][j]; ma[i][j] = ma[i][k]; ma[i][k] = a; } } } }
The logic used to sort the columns in descending order is as follows −
for (j=0;j<n;++j){ for (i=0;i<m;++i){ for (k=i+1;k<m;++k){ if (mb[i][j] < mb[k][j]){ a = mb[i][j]; mb[i][j] = mb[k][j]; mb[k][j] = a; } } } }
The following is a C program to sort all the columns of the matrix in ascending order Rows are sorted and all columns are sorted in descending order −
Live Demonstration
#include <stdio.h> void main(){ int i,j,k,a,m,n; static int ma[10][10],mb[10][10]; printf ("Enter the order of the matrix </p><p>"); scanf ("%d %d", &m,&n); printf ("Enter co-efficients of the matrix </p><p>"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ scanf ("%d",&ma[i][j]); mb[i][j] = ma[i][j]; } } printf ("The given matrix is </p><p>"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("</p><p>"); } printf ("After arranging rows in ascending order</p><p>"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ for (k=(j+1);k<n;++k){ if (ma[i][j] > ma[i][k]){ a = ma[i][j]; ma[i][j] = ma[i][k]; ma[i][k] = a; } } } } for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("</p><p>"); } printf ("After arranging the columns in descending order </p><p>"); for (j=0;j<n;++j){ for (i=0;i<m;++i){ for (k=i+1;k<m;++k){ if (mb[i][j] < mb[k][j]){ a = mb[i][j]; mb[i][j] = mb[k][j]; mb[k][j] = a; } } } } for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",mb[i][j]); } printf ("</p><p>"); } }
When the above program is executed, it produces the following result −
Enter the order of the matrix 3 4 Enter co-efficient of the matrix 1 2 3 4 1 2 3 4 5 1 2 3 The given matrix is 1 2 3 4 1 2 3 4 5 1 2 3 After arranging rows in ascending order 1 2 3 4 1 2 3 4 1 2 3 5 After arranging the columns in descending order 5 2 3 4 1 2 3 4 1 1 2 3
The above is the detailed content of C program to sort all columns and rows of a matrix. For more information, please follow other related articles on the PHP Chinese website!