Change the quadrants of an even-sized matrix

Asked

Viewed 146 times

0

I get an array, and I must print it on the screen as shown in the image below.


Como deve ser a saída


This is the current code:


#include<stdio.h>

int main(){

    int matriz[4][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
    int l, c;


    for(l = 0; l < 4; l++){
        for(c = 0; c < 4; c++){
            printf("%2.i ", matriz[l][c]);
        }
        printf("\n");
    }

    printf("\n");

    for(l = 0; l < 4; l++){
        for(c = 0; c < 4; c++){
            if(l >= 0 && c <= 1){
                printf("%i ", matriz[l+2][c+2]);    
            }else if(l >= 0 && c >=2){
                printf("%i ", matriz[l+2][c-2]);    
            }else if(l >= 2 && c <= 1){
                printf("%i ", matriz[l-2][c+2]);    
            }else if(l >= 2 && c >= 2){
                printf("%i ", matriz[l-2][c-2]);    
            }
        }
        printf("\n");
    }


return 0;   
}

And this is the result that I got, for some reason is picking up the memory garbage, and not the values of the matrix when printing the bottom, the top is correct, but the bottom is not getting, someone knows how to solve and give me a light ? thank you very much.

Resultado que obtive com o código atual

1 answer

0


Some of your validations were wrong, if you validate l>=0 will allow any l between this condition, this happened in the first two ifs, the correct validation is l<2, see below:

#include<stdio.h>
int main(){

int matriz[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int l, c;


for(l = 0; l < 4; l++){
    for(c = 0; c < 4; c++){
        printf("%2.i ", matriz[l][c]);
    }
    printf("\n");
}

printf("\n");

for(l = 0; l < 4; l++){
    for(c = 0; c < 4; c++){
        if(l < 2 && c <= 1){
            printf("%i ", matriz[l+2][c+2]);    
        }else if(l < 2 && c >=2){
            printf("%i ", matriz[l+2][c-2]);    
        }else if(l >= 2 && c <= 1){
            printf("%i ", matriz[l-2][c+2]);    
        }else if(l >= 2 && c >= 2){
            printf("%i ", matriz[l-2][c-2]);    
        }
    }
    printf("\n");
}
return 0;
}
  • 1

    Oh man, thanks, that’s right, so silly mistake of lack of attention that cost me 5 months kkkkkk, I’m from November last year trying to solve this problem, only with a picture, thank you very much

Browser other questions tagged

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