Instead of x + 2 and x - 2 which will only work if you are informed 4 to n, use x + n / 2 and x - n / 2.
What is repeated within the two ifs can be moved to before or after them.
Remember that the first index is zero. This means that your if (x<=(n/2)), in a four-line matrix, will go to the third line, and not to the second. What you wanted was to use the < instead of <=.
Instead of using if ( x==3 ||(x>(n/2))), just use else. Also, due to the previous item, it should be >= instead of >, which would eliminate the need for this x==3.
In the printf of the first if, you use matriz[x][y], but the second one uses matriz[x-2][y].
You also don’t need a lot of variables aux, only one is needed.
Here’s what your code looks like with these fixes:
int matriz[TAM][TAM], n = 0, x = 0, y = 0;
printf("Informe um tamanho par para sua matriz: \n");
scanf("%d", &n);
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
printf("Preencha a matriz: \n");
scanf("%d", &matriz[x][y]);
}
}
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
int aux = matriz[x][y];
if (x < n / 2) {
matriz[x][y] = matriz[x + n / 2][y];
matriz[x + n / 2][y] = aux;
} else {
matriz[x][y] = matriz[x - n / 2][y];
matriz[x - n / 2][y] = aux;
}
printf("%d ", matriz[x][y]);
}
printf("\n");
}
It is possible to simplify your code a little more and unify the if and the else when checking the position of the line you want to exchange (let’s call nx) can be calculated from x thus:
int nx = (x + n / 2) % n;
To see how this works, see that being n equal to 4, we will have to:
- If
x for 0, nx will be 2.
- If
x for 1, nx will be 3.
- If
x for 2, nx will be 0.
- If
x for 3, nx will be 1.
This will work for any other even value of n.
This way, your code looks like this:
int matriz[TAM][TAM], n = 0, x = 0, y = 0;
printf("Informe um tamanho par para sua matriz: \n");
scanf("%d", &n);
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
printf("Preencha a matriz: \n");
scanf("%d", &matriz[x][y]);
}
}
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
int nx = (x + n / 2) % n;
int aux = matriz[x][y];
matriz[x][y] = matriz[nx][y];
matriz[nx][y] = aux;
printf("%d ", matriz[x][y]);
}
printf("\n");
}
I understand perfectly. Thank you for your great help!
– french kote.