I am trying to write a program that takes inputs on the amount of rows and columns of a given matrix. Then I would like to ask the user to input the values on each indice, then print out the array.
I accomplished this by doing:
int main() {
int rows, columns;
int i, j;
printf("Enter amount of rows: ");
scanf("%d", &rows);
printf("Enter amount of columns: ");
scanf("%d", &columns);
int array[rows][columns];
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++){
printf("Enter element of row %d and column %d: ", i + 1, j + 1);
scanf("%d", &array[i][j]);
}
}
printf("You entered:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
if (j == 0)
printf("[ ");
printf("%d ", array[i][j]);
if (j == columns - 1)
printf("]\n");
}
}
printf("-----------------------------\n");
This part of the code gives expected output. Whenever the amount of rows and columns are the same, I get my expected output as well. e.g:
You entered:
[ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ]
-----------------------------
Transposed matrix:
[ 1 4 7 ]
[ 2 5 8 ]
[ 3 6 9 ]
Whenever there are more columns than rows, I get expected output as well.
You entered:
[ 1 2 3 4 5 ]
[ 6 7 8 9 10 ]
[ 11 12 13 14 15 ]
-----------------------------
Transposed matrix:
[ 1 6 11 ]
[ 2 7 12 ]
[ 3 8 13 ]
[ 4 9 14 ]
[ 5 10 15 ]
However, whenever there are more rows than columns, that's where the issue seems to arise. For example:
You entered:
[ 1 2 ]
[ 3 4 ]
[ 5 6 ]
-----------------------------
Transposed matrix:
[ 1 3 2 ]
[ 2 4 5 ]
This is the code responsible for the transposing. It is right under the print statement with multiple dashes. Any help or insight as to why this isn't working would be great.
for (i = 0; i < columns; i++){
for (j = 0; j < i; j++) {
int *transposedRow = &array[0][0] + (i * columns + j);
int *transposedCol = &array[0][0] + (j * columns + i);
int temp;
temp = *transposedRow;
*transposedRow = *transposedCol;
*transposedCol = temp;
}
}
printf("Transposed matrix:\n");
for (i = 0; i < columns; i++) {
for (j = 0; j < rows; j++) {
if (j == 0)
printf("[ ");
printf("%d ", array[i][j]);
if (j == rows - 1)
printf("]\n");
}
}