HomeAbout UsContact Us

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

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

Table Of Contents

01
Code Walkthrough
02
Frequently Asked Questions

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.

Frequently Asked Questions

What is the main performance consideration when transposing a matrix in C?

C stores arrays in row-major order. When transposing, you inevitably access memory column-wise, which causes CPU cache misses. For large matrices, cache-oblivious or block-transposed algorithms are preferred.

Why must the matrix be a square matrix for in-place transposing?

In-place transposing swaps elements `matrix[i][j]` and `matrix[j][i]`. If the matrix is not square (rows != columns), the dimensions change, requiring memory allocation for a new destination layout.

What is the time complexity of a square matrix transpose?

The time complexity is O(N^2) where N is the number of rows/columns. You only need to iterate through the upper or lower triangle of the matrix to swap the elements.

Tags

embedded cprogrammingmatrix

Share


Previous Article
C Program to implement custom mutex_lock() and mutex_unlock()
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Understanding the volatile Keyword in Embedded C
Understanding the volatile Keyword in Embedded C
May 08, 2026
3 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media