/* * To sort the columns of a 3 X 3 matrix in ascending order of their sums * @author-Karan Narain(karan@iitk.ac.in) * */ #include int main() { int A[3][3],sum[3],i,j,k,temp; //initialize the sum array to 0 for(i=0;i<3;i++) sum[i]=0; printf("Enter the 3 X 3 matrix\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&A[i][j]); //Add this element to the corresponding column sum sum[j]=sum[j]+A[i][j]; } } //Sort the sum array using bubble sort,i.e.compare each element with its neighbour and send the largest element in every iteration to the end of the array for(i=0;i<3;i++) { for(j=0;j<2;j++) { if(sum[j]>sum[j+1]) { //swap the elements temp=sum[j]; sum[j]=sum[j+1]; sum[j+1]=temp; //After swapping two elements of the sum array,swap the corresponding columns having those sums too.The variable k is used for row indices for(k=0;k<3;k++) { temp=A[k][j]; A[k][j]=A[k][j+1]; A[k][j+1]=temp; } } } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d ",A[i][j]); } printf("\n"); } }