Declare the matrix: Initially, we must define a 2D array to depict the matrix. This can be accomplished by specifying the row and column quantities in the subsequent manner:
int matrix[m][n];
Here, m and n symbolize the number of rows and columns, respectively.
Set up the matrix: To begin, we must set up the matrix by assigning initial values. This can be achieved by employing a nested for loop in the manner demonstrated below:
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
scanf("%d", &matrix[i][j]); //input values using scanf function
}
}
Here, we are employing the scanf function to input values into the matrix.
Once the matrix is set up, we can perform a matrix transposition by employing an additional nested for loop in the following manner:
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
Here, we are interchanging the elements of the matrix across the diagonal. This process involves saving the element's value at matrixi in a temporary variable, exchanging the values of matrixi and matrixj, and then setting the temporary variable's value to matrixj.
Show the transposed matrix by utilizing an additional nested for loop, like this:
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
Here, we are employing the printf function to showcase the components of the transposed matrix.
Combining all the components, we obtain the subsequent full program:
C Program:
#include<stdio.h>
int main(){
int m, n;
printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);
int matrix[10^5][10^5];
printf("Enter the elements of the matrix:\n");
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
scanf("%d", &matrix[i][j]);
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
printf("The transposed matrix is:\n");
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 3
Enter the number of columns: 2
Enter the elements of the matrix:
1 2
2 3
3 4
The transposed matrix is:
1 2 3
2 3 4
This software requests the user to provide the dimensions of the matrix, sets up the matrix with values entered by the user, performs a transpose operation on the matrix, and finally presents the transposed matrix to the user. It is important to emphasize that the program expects the user to input accurate values for both the matrix dimensions and its elements.