C Online Compiler
Example: Transpose of Matrix With Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Transpose of Matrix With Function #include <stdio.h> #define MAX_ROWS 10 #define MAX_COLS 10 // Function to calculate and store the transpose of a matrix void transposeMatrix(int original[MAX_ROWS][MAX_COLS], int rows, int cols, int result[MAX_COLS][MAX_ROWS]) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[j][i] = original[i][j]; } } } // Function to print a matrix void printMatrix(int matrix_to_print[][MAX_COLS], int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix_to_print[i][j]); } printf("\n"); } } int main() { int actual_rows = 3; int actual_cols = 2; int matrix[MAX_ROWS][MAX_COLS] = {{1, 2}, {3, 4}, {5, 6}}; // Original matrix int transpose[MAX_COLS][MAX_ROWS]; // Transposed matrix // Step 1: Print the original matrix printf("Original Matrix (%dx%d):\n", actual_rows, actual_cols); printMatrix(matrix, actual_rows, actual_cols); // Step 2: Calculate the transpose using the function transposeMatrix(matrix, actual_rows, actual_cols, transpose); // Step 3: Print the transposed matrix printf("\nTransposed Matrix (%dx%d):\n", actual_cols, actual_rows); // Note: For printMatrix, the matrix_to_print argument needs to be cast or adjusted // when passing 'transpose' because its column size is actual_rows, not MAX_COLS. // A more robust print function would handle arbitrary 2D array dimensions // or take a base pointer and dimensions. For simplicity, we'll print manually here. for (int i = 0; i < actual_cols; i++) { for (int j = 0; j < actual_rows; j++) { printf("%d ", transpose[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS