C Online Compiler
Example: Matrix Transpose using Functions in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Transpose using Functions #include <stdio.h> // Function to read elements of a matrix void readMatrix(int rows, int cols, int matrix[rows][cols]) { printf("Enter elements of the matrix (%d x %d):\n", rows, cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element [%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } } } // Function to print a matrix void printMatrix(int rows, int cols, int matrix[rows][cols]) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } } // Function to find the transpose of a matrix void transposeMatrix(int rows, int cols, int originalMatrix[rows][cols], int transposedMatrix[cols][rows]) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { transposedMatrix[j][i] = originalMatrix[i][j]; } } } int main() { int rows, cols; // Step 1: Get matrix dimensions 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); // Step 2: Declare original and transposed matrices using Variable Length Arrays (VLAs) // VLAs are a C99 feature; for older C standards, dynamic allocation or fixed size arrays are needed. int originalMatrix[rows][cols]; int transposedMatrix[cols][rows]; // Transposed matrix will have cols rows and rows cols // Step 3: Read elements into the original matrix using a function readMatrix(rows, cols, originalMatrix); // Step 4: Print the original matrix using a function printf("\nOriginal Matrix:\n"); printMatrix(rows, cols, originalMatrix); // Step 5: Compute the transpose using a function transposeMatrix(rows, cols, originalMatrix, transposedMatrix); // Step 6: Print the transposed matrix using a function printf("\nTransposed Matrix:\n"); printMatrix(cols, rows, transposedMatrix); // Note: dimensions are swapped for printing return 0; }
Output
Clear
ADVERTISEMENTS