Invert row with column in a matrix?

Asked

Viewed 1,515 times

0

Make a program that randomly generates 20 integers in the range of 0 to 999 and fill in a matrix of size 5 x 4. Show the matrix, then show the transposed matrix (reverse row with column).

I’ve managed to fill the matrix with random numbers only I can’t transpose.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
  int i, j, matriz[5][4], matriz5[4][5];
  srand(time(NULL));

   for (i = 0; i < 5; i++)
       for(j = 0; j < 4; j++)
           matriz[i][j] = rand()%999;

   for (i = 0; i < 5; i++){
        for(j = 0; j < 4; j++){
           printf(" %d ",matriz[i][j]);
       }
       printf("\n");
   }

  return 0;
}

1 answer

0


To find the transpose of the matrix just invert the indices in the assignment of values, the row goes to the column and vice versa.

Exemplifying in your code, creating the transposed matrix in matriz5:

for (i = 0; i < 5; i++) {
    for(j = 0; j < 4; j++) {
        matriz5[j][i] = matriz[i][j];
        //      ^--^-----------^--^
    }
}

Then pay attention when showing because the boundaries of rows and columns will also be reversed:

for (i = 0; i < 4; i++) {
//              ^--- 
    for(j = 0; j < 5; j++) {
    //             ^---
        printf(" %d ", matriz5[i][j]);
    }
    printf("\n");
}

Watch it work on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.