Arrays: Transpose of a matrix

supriyo_biswas · updated November 16, 2019 · C
#include <stdio.h>

int main() {
    // declare input and output array, and variables
    // for the number of rows and columns. there are
    // also two loop variables i and j.
    int a[10][10], b[10][10], rows, cols, i, j;

    printf("Enter the number of rows:\n");
    scanf("%d", &rows);

    printf("Enter the number of columns:\n");
    scanf("%d", &cols);

    // check if the number of rows/columns requested
    // is too small or too large
    if (rows < 1 || cols < 1 || rows > 10 || cols > 10) {
        printf("Invalid number of rows or columns\n");
        // exit the program
        return 0;
    }

    // ask for all the numbers
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            // array index starts from 0, but row or
            // column number starts from 1.
            printf("Enter row %i, column %i:\n", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }
    }

    printf("The input matrix is:\n");

    // print the input matrix
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            printf("%d ", a[i][j]);
        }

        // to seperate the rows
        printf("\n");
    }

    // calculate the transpose of the matrix
    // order of rows and columns is swapped because
    // a[row][col] becomes b[col][row]
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            b[j][i] = a[i][j];
        }
    }

    printf("Transpose of the matrix is:\n");

    // print the transpose.
    // number of rows in input matrix becomes number of
    // columns in the output matrix; similarly, number
    // of columns in input matrix becomes number of
    // columns in output matrix. this is why we have used
    // cols in the outer loop and rows in the inner loop
    for (i = 0; i < cols; i++) {
        for (j = 0; j < rows; j++) {
            printf("%d ", b[i][j]);
        }

        // to seperate the rows
        printf("\n");
    }

    return 0;
}

Comments

Please sign up or log in to contribute to the discussion.