Thursday, November 27, 2014

C Program for sorting the rows and interchanging the columns

/*......................................................................................................................................
File : rec12.c
program : Menu driven program for
(1) Exchange the values of the two columns of a matrix m*n
(2) Sort the each rows of a matrix
Author : sujithbaby440@gmail.com
Date :13/11/2014
........................................................………………………………………………………….*/
#include<stdio.h>
main()
{
int i,j,m,n,a[30][30],choice,c1,c2,temp,x,y;
system("clear");
printf("Program for sorting the rows and interchanging the columns\n");
printf("\nEnter the number of rows and columns\n");
scanf("%d%d",&m,&n);
printf("Enter the elements into the %d*%d matrix\n",m,n);
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
scanf("%d",&a[i][j]);
}
}
printf("Matrix:\n");
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
printf(" Select your choice\n");
printf("\n (1) Exchange the values of the two columns of a matrix m*n");
printf("\n (2) Sort the each rows of a matrix\n");
scanf("%d",&choice);
if(choice==1){
printf("Enter the columns which are to be interchanged \n");
scanf("%d%d",&c1,&c2);
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
if(j==c1){
temp=a[i][c1];
}if(j==c2){
a[i][c1]=a[i][c2];
a[i][c2]=temp;
}
}
}
printf("the interchanged matrix :\n");
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
}else if(choice==2){
printf("Sort all rows in the given matrix\n");
for(i=1;i<=m;i++){
for(x=1;x<=m-1;x++){
for(y=1;y<=m-x;y++){
if(a[i][y]>a[i][y+1]){
temp=a[i][y];
a[i][y]=a[i][y+1];
a[i][y+1]=temp;
}
}
}
}
printf("sorted Matrix:\n");
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
}
}

OUTPUT 1
Program for sorting the rows and interchanging the columns
Enter the number of rows and columns
3 3
Enter the elements into the 3*3 matrix
1 2 3
4 5 6
7 8 9
Matrix:
1 2 3
4 5 6
7 8 9
Select your choice
(1) Exchange the values of the two columns of a matrix m*n
(2) Sort the each rows of a matrix
1
Enter the columns which are to be interchanged
1 3
the interchanged matrix :
3 2 1
6 5 4
9 8 7
[141740@localhost ~]$


OUTPUT 2
Program for sorting the rows and interchanging the columns
Enter the number of rows and columns
3 3
Enter the elements into the 3*3 matrix
4 5 8
1 1 3
7 9 6
Matrix:
4 5 8
1 1 3
7 9 6
Select your choice
(1) Exchange the values of the two columns of a matrix m*n
(2) Sort the each rows of a matrix
2
Sort all rows in the given matrix
sorted Matrix:
4 5 8
1 1 3
6 7 9
[141740@localhost ~]$

No comments:

Post a Comment