Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Transpose of matrix

In this example , we will find the Transpose of matrix

#include <iostream>
using namespace std;
const int MAX = 100;

void transpose(int arr[][MAX], int m, int n){
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            cout<<arr[j][i]<<" ";
        }
        cout<<endl;
    }
}

int main(){
    int arr[4][MAX] = {{1,2,4,5},
                       {5,8,5,9},
                       {7,8,9,4},
                       {4,8,9,6}};
                
    transpose(arr,4,4);
    return 0;
}

Output:

1 5 7 4 
2 8 8 8 
4 5 9 9 
5 9 4 6

Explanation:

Step1 : Constants

const int MAX = 100;

This defines a constant MAX which sets the maximum size of the matrix (100 columns). It is used to limit the size of the 2D array.

Step2 : transpose Function

void transpose(int arr[][MAX], int m, int n){
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            cout<<arr[j][i]<<" ";
        }
        cout<<endl;
    }
}

This function prints the transpose of the matrix. It takes three parameters:

  • arr[][MAX]: A 2D array (matrix) of integers where the second dimension is limited by MAX.
  • m: The number of rows in the matrix.
  • n: The number of columns in the matrix.

Within the function:

  • The outer loop (i) iterates over the rows.
  • The inner loop (j) iterates over the columns.
  • arr[j][i] accesses the element in the transposed position, flipping rows and columns.
  • It prints each transposed element, and after each row is printed, cout << endl is used to move to the next line.

Step3: Main Function

int main(){
    int arr[4][MAX] = {{1,2,4,5},
                       {5,8,5,9},
                       {7,8,9,4},
                       {4,8,9,6}};
                
    transpose(arr,4,4);
    return 0;
}

In the main() function:

  • A 4×4 matrix arr is declared and initialized with specific values.
  • The transpose(arr, 4, 4) function is called, passing the matrix and its dimensions (4×4) as arguments.
  • The transposed matrix is printed to the console.

    Leave a Reply

    Your email address will not be published.

    Need Help?