简体   繁体   中英

a program for transposing a matrix but in this program in printing result it has a bug

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

    int main(){
        int m,n,i,j,t;
        printf("in order enter line and column of matrix :");
        scanf("%d%d",&n,&m);
        int a[n][m],b[m][n];
        for(i=0;i<n;i++){
            for(j=0;j<m;j++){
                printf("a[%d][%d]= ",i+1,j+1);
                scanf("%d",&a[i][j]);
              }
          }
        printf("first matrix:\n");
        for(i=0;i<n;i++){
            for(j=0;j<m;j++){
                printf("%d    ",a[i][j]);
              }
              printf("\n\n");
          }
        for(i=0;i<n;i++){
            for(j=0;j<m;j++){
                b[j][i]=a[i][j];
            }
        }
        printf("transposed matrix:\n");
        for(i=0;i<m;i++){
            for(j=0;j<n;j++){
                printf("%d    ",b[j][i]);
              }
              printf("\n\n");
        }

      }

a program for transposing a matrix but in this program in printing result it has a bug, for example, this program for a Square matrix print first matrix

You've interchanged the row and column indices. Printing b[i][j] works fine. Even with non square matrices.

printf("transposed matrix:\n");
for(i=0;i<m;i++)
{
    for(j=0;j<n;j++)
    {
        printf("%d    ",b[i][j]);
    }
    printf("\n\n");
 }

Here is an example:

a[1][1]= 1
a[1][2]= 2
a[2][1]= 3
a[2][2]= 4
a[3][1]= 5
a[3][2]= 6
first matrix:
1    2    

3    4    

5    6    

transposed matrix:
1    3    5    

2    4    6 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM