C Online Compiler
Example: Transpose of a Square Matrix in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Transpose of a Square Matrix #include <stdio.h> #define SIZE 3 // Define the size of the square matrix int main() { // Step 1: Declare and initialize the original square matrix int originalMatrix[SIZE][SIZE] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Step 2: Declare a new matrix to store the transpose int transposedMatrix[SIZE][SIZE]; // Step 3: Print the original matrix printf("Original Matrix:\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%d ", originalMatrix[i][j]); } printf("\n"); } // Step 4: Compute the transpose // Iterate through rows of the original matrix for (int i = 0; i < SIZE; i++) { // Iterate through columns of the original matrix for (int j = 0; j < SIZE; j++) { // Assign element at (i, j) of original to (j, i) of transposed transposedMatrix[j][i] = originalMatrix[i][j]; } } // Step 5: Print the transposed matrix printf("\nTransposed Matrix:\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%d ", transposedMatrix[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS