Home »
C programs »
C two-dimensional arrays programs
C program to interchange the columns in the matrix
Here, we are going to learn how to interchange the columns in the matrix in C programming language?
Submitted by Nidhi, on July 13, 2021
Problem Solution:
Given a matrix, and we have to interchange the specified columns using C program.
Program:
The source code to interchange the columns in the matrix is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to interchange the columns in matrix
#include <stdio.h>
int main()
{
int Matrix[3][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int i, j, n1, n2, temp;
printf("Matrix before column exchange:\n");
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j)
printf(" %d", Matrix[i][j]);
printf("\n");
}
printf("Enter two column numbers to be exchanged:");
scanf("%d %d", &n1, &n2);
//Exchange columns
for (i = 0; i < 3; ++i) {
temp = Matrix[i][n1 - 1];
Matrix[i][n1 - 1] = Matrix[i][n2 - 1];
Matrix[i][n2 - 1] = temp;
}
printf("Matrix after column exchange:\n");
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j)
printf(" %d", Matrix[i][j]);
printf("\n");
}
return 0;
}
Output:
RUN 1:
Matrix before column exchange:
1 2 3
4 5 6
7 8 9
Enter two column numbers to be exchanged:1 3
Matrix after column exchange:
3 2 1
6 5 4
9 8 7
RUN 2:
Matrix before column exchange:
1 2 3
4 5 6
7 8 9
Enter two column numbers to be exchanged:1 2
Matrix after column exchange:
2 1 3
5 4 6
8 7 9
RUN 3:
Matrix before column exchange:
1 2 3
4 5 6
7 8 9
Enter two column numbers to be exchanged:2 3
Matrix after column exchange:
1 3 2
4 6 5
7 9 8
Explanation:
In the main() function, we created a 3X3 matrix matrix using the 2D array. Then we read column numbers to be exchanged. After that, we interchanged the columns and printed the updated matrix on the console screen.
C Two-dimensional Arrays Programs »