Write a C Program to Find Transpose of a Matrix.

#include<stdio.h>

int main()  // main function which returns integer value
{
    int r, c, i, j;     //declaration of integer variables
    printf(">> Enter rows and columns of matrix: ");    // print statement to get size of rows and cols
    scanf("%d %d", &r, &c);     // run time initialization for 'r' and 'c'

    // here we have two multi dimentional arrays of type integer.. 1) 'a' 2) 'transpose'
    int a[r][c], transpose[r][c];   // declaration of array with run time size allocation.

    // Storing elements of the matrix
    printf("\nEnter %d elements of matrix:\n",(r*c));   // printing total elements to insert in array.
    for(i=0; i<r; i++)  // for loop to iterate rows
        for(j=0; j<c; j++)  // for loop to iterate columns
        {
            printf("Enter element a[%d][%d]: ",i, j);   // printing array index
            scanf("%d", &a[i][j]);  // initializing or inserting elements to an array 'a' => runtime initialization
        }

    // Displaying the matrix a[][]
    printf("\nEntered Matrix: \n");
    for(i=0; i<r; i++)
    {
        for(j=0; j<c; j++)
        {
            printf("%d\t", a[i][j]);
        }
        printf("\n\n");
    }

    // Finding the transpose of matrix a
    for(i=0; i<r; i++)
        for(j=0; j<c; j++)
            transpose[j][i] = a[i][j];

    // Displaying the transpose of matrix a
    printf("\nTranspose of Matrix:\n");
    for(i=0; i<c; i++)
    {
        for(j=0; j<r; j++)
        {
            printf("\a%d\t",transpose[i][j]);
        }
        printf("\n\n");
    }
}

Comments