I am trying to display the values stored in a 4x5 matrix by rows and columns, separately. However, the columns are printed to me in the same order as the values stored in rows. In addition, in the last values returned they do not correspond and are a row of meaningless numbers. I don't know if it's the fault of using an online C compiler that doesn't handle so much data correctly, because only in one of the executions has it correctly printed the values stored by columns. What's going on?
#include <stdio.h>
#define m 4
#define n 5
int main () {
puts("Este programa almacenará los elementos de una matriz 4x5 y mostrará los valores de filas y columnas por separado.");
int matriz[m][n];
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
printf("\nIntroduzca el elemento almacenado en la fila %d y columna %d: ", i+1, j+1);
scanf("%d", &matriz[i][j]);
}
}
puts("\n\nElementos almacenados en las distintas filas de la matriz: ");
for (int i=0; i<m; i++) {
printf("\nFILA %d:", i+1);
for (int j=0; j<n; j++) {
printf(" %d", matriz[i][j]);
}
}
puts("\n\nElementos almacenados en las distintas columnas de la matriz: ");
for (int j=0; j<n; j++) {
printf("\nCOLUMNA %d:", j+1);
for (int i=0; i<m; i++) {
printf(" %d", matriz[j][i]);
}
}
return 0;
}
The problem is that you mix the way of traversing the array with the way of painting it.
That is, you have M rows, N columns. By feeding the array, you have the variable
i
that goes to < M,j
goes to < N. All goodYour example has M=4 (0,1,2,3), N=5 (0,1,2,3,4).
You paint by rows and all good.
THEN, you are going to paint by columns. You iterate first through N and then through M. Good. BUT you give inverted indices to the array.
For example, in the boundary case,
i=3, j=4
, you are looking for the positionmatriz[4][3]
that does not exist. So you are accessing memory locations that are not yours :PIf you reverse the way you go BUT respect the boundaries, you're going to get what you need I think
output is