C program to swap the rows-to-columns for any square matrix

Published in Embedded C/C++
September 08, 2025
1 min read
C program to swap the rows-to-columns for any square matrix

This is essentially asking for a transpose of a square matrix (rows become columns and vice versa). Below is a simple program to implement this problem,

#include <stdio.h>
#define MAX 10 // maximum size of the matrix
// Function to print the matrix
void printMatrix(int matrix[MAX][MAX], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int n;
int matrix[MAX][MAX];
printf("Enter the size of the square matrix (n x n): ");
scanf("%d", &n);
if (n > MAX) {
printf("Error: Maximum size allowed is %d\n", MAX);
return 1;
}
printf("Enter the elements of the %d x %d matrix:\n", n, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("\nOriginal Matrix:\n");
printMatrix(matrix, n);
// Transpose in place (swap rows and columns)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
printf("\nMatrix after swapping rows to columns (Transpose):\n");
printMatrix(matrix, n);
return 0;
}

Code Walkthrough

  1. The user enters the size n and the n x n matrix.
  2. We print the original matrix.
  3. To transpose: for each pair (i, j) above the diagonal, we swap matrix[i] with matrix[j].
  4. This avoids double-swapping and keeps the diagonal elements unchanged.
  5. Finally, we print the transposed matrix.