The matrix you created is equal to:
| 0 | 1 | 2 | 3 | 4 |
| 1 | 2 | 3 | 4 | 5 |
| 2 | 3 | 4 | 5 | 6 |
| 3 | 4 | 5 | 6 | 7 |
| 4 | 5 | 6 | 7 | 8 |
I mean, it’s a symmetrical matrix, which means it is equal to your transpose. Therefore, it is not a good example for you to test if the function transposta
is working.
So first let’s modify the first one a little bit loop:
for (int i = 0, c = 0; i < 5; i++) {
for (int j = 0; j < 5; j++, c++) {
matriz[i][j] = c;
}
}
This creates the following matrix:
| 0 | 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 |
Now yes we can get the transpose and know if it worked.
Since the matrix is square, you don’t need to go through all the elements. The diagonal remains the same, and you only need to traverse one of the "halves" (or the "right" or "left" part of the diagonal) and switch to the corresponding "opposite" position:
void transposta(int matriz[][5]) {
for (int i = 1; i < 5; i++) { // começa em 1, pois ignora a diagonal
for (int j = 0; j < i; j++) { // só vai até `i` (até a diagonal), não precisa ir até o fim
// troca os elementos de posição
int aux = matriz[i][j];
matriz[i][j] = matriz[j][i];
matriz[j][i] = aux;
}
}
}
int main(void) {
int matriz[5][5];
for (int i = 0, c = 0; i < 5; i++) {
for (int j = 0; j < 5; j++, c++) {
matriz[i][j] = c;
}
}
printf("original:\n");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
printf("| %2d ", matriz[i][j]);
}
printf("|\n");
}
transposta(matriz);
printf("transposta:\n");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
printf("| %2d ", matriz[i][j]);
}
printf("|\n");
}
}
I also changed the output a little bit: you were printing ||
between elements, changed to print only one. The output is:
original:
| 0 | 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 |
transposta:
| 0 | 5 | 10 | 15 | 20 |
| 1 | 6 | 11 | 16 | 21 |
| 2 | 7 | 12 | 17 | 22 |
| 3 | 8 | 13 | 18 | 23 |
| 4 | 9 | 14 | 19 | 24 |
What is happening is that you are swapping out cda element twice, which makes it the same as the original. Try:
for (int i = 0; i < 5; i++) {
 for (int j = i+1; j < 5; j++) {
 int aux = MatrizA[i][j];
 MatrizA[i][j] = MatrizA[j][i];
 MatrizA[j][i] = aux;
 }
 }
.– anonimo