Interchange any two rows in a matrix
C program to interchange any two rows in a matrix.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void interchange_row(int mat[MAX][MAX], int row, int col, int row1, int row2)
{
int i, j, temp;
for(i=0;i<col;i++)
{
temp = mat[row1][i];
mat[row1][i] = mat[row2][i];
mat[row2][i] = temp;
}
}
void main()
{
int mat[MAX][MAX];
int row, col, row1, row2;
printf("Enter the number of rows\t:");
scanf("%d",&row);
printf("Enter the number of columns\t:");
scanf("%d",&col);
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("Enter the indexes of the rows to be interchanged (0 to %d)\t:",row-1);
scanf("%d%d",&row1, &row2);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
interchange_row(mat, row, col, row1, row2);
printf("\nMatrix after interchanging of rows\n");
print_matrix(mat, row, col);
getch();
}
Output
Enter the number of rows :3
Enter the number of columns :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [1][0] :5
Element [1][1] :6
Element [1][2] :7
Element [1][3] :8
Element [2][0] :9
Element [2][1] :10
Element [2][2] :11
Element [2][3] :12
Enter the indexes of the rows to be interchanged (0 to 2) :0
2
Matrix entered is
1 2 3 4
5 6 7 8
9 10 11 12
Matrix after interchanging of rows
9 10 11 12
5 6 7 8
1 2 3 4