C Online Compiler
Example: Matrix Transpose using Arrays in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Transpose using Arrays #include <stdio.h> int main() { int rows, cols; // Step 1: Get dimensions of the matrix from the user printf("Enter the number of rows for the matrix: "); scanf("%d", &rows); printf("Enter the number of columns for the matrix: "); scanf("%d", &cols); int matrix[rows][cols]; int transpose[cols][rows]; // Transpose matrix will have dimensions cols x rows // Step 2: Read elements of the original matrix printf("\nEnter elements of the matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element matrix[%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } } // Step 3: Print the original matrix printf("\nOriginal Matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } // Step 4: Compute the transpose for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { transpose[j][i] = matrix[i][j]; } } // Step 5: Print the transposed matrix printf("\nTransposed Matrix:\n"); for (int i = 0; i < cols; i++) { // Note: iterate with cols and rows swapped for (int j = 0; j < rows; j++) { printf("%d\t", transpose[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS