-1

Ok so i wanna make a code thats gonna print a magic square that works like the one in the picture (https://i.stack.imgur.com/q3vud.jpg) ( which is a 5x5 matrix ) but it is 11x11.Code seems fine to me but unfortunately it doesnt work , can anyone help me ?

int main(int argc, char *argv[]) {
int i, j,k,l;   

int a[10][10] = {0} ;

k=5;

l=5;

a[k][l]=1;

for (i=1; i<11; i++) {

    if (i%2!=0){

        for (j=0; j<i; j++) {
            a[k][l+1]=a[k][l] + 1;
            l++;    }

        for (j=0;j<i;j++) {
            a[k+1][l]= a[k][l] + 1;
            k++;    }

    }

    if (i%2==0){

        for (j=0; j<i; j++){
            a[k][l-1]= a[k][l] + 1;
            l--;    }

        for (j=0; j<i; j++){
            a[k-1][l]= a[k][l] + 1;
            k--;    }
    }

    if (i==10){

        for (j=0; j<10; j++){

            a[k][l+1]=a[k][l] + 1;
            l++;
        }
    }
}
for(i=0; i<11;i++){

    for(j=0;j<11;j++){

        printf("%d ", a[i][j]); }

    printf("\n");
}


return 0;
}

Ok so i fixed it to be a[11][11] ( stupid mistake ) , but it gets printed like that ( https://i.stack.imgur.com/HS2pF.jpg ) , why is that ?

  • You write out of bounds of `a`. Valid indices for `int a[10][10]` are `0` through `9`. – M.M Mar 18 '16 at 02:35
  • Ok so i fixed it to be a[11][11] ( stupid mistake ) , but it gets printed like that ( http://imgur.com/ai221Pu ) , why is that ? – Chrysteria Mar 18 '16 at 03:39

1 Answers1

0

The code isn't really that clear, but check the declaration size

int a[10][10] = {0} ;

When declaring an array the values placed inside correspond to the actual size starting from 1, not from 0 like when accessing them. This MIGHT result in a segmentation fault (going outside the memory reserved for your program to run in),but will probably only result in printing out random numbers since you're only going beyond about 44/88 bytes(depending on the int size). Instead declare the structure as following and please use a logical name not random labels, as it helps A LOT with program interpretation:

int magic_square[11][11];

Edit: Also check your indentation since it's off by one tab

Mr. Branch
  • 442
  • 2
  • 13
  • Ok so i fixed it to be a[11][11] ( stupid mistake ) , but it gets printed like that ( imgur.com/ai221Pu ) , why is that ? – Chrysteria Mar 18 '16 at 04:19
  • The problem is the spacing in printf you can fix that with the width specifier in printf. simple add the amount of digits you will print before the number specifier and number with less than that amount of digits will be left padded with spaces. Ex: printf("%3d ", a[i][j]); Here's the complete reference guide to printf: http://www.cplusplus.com/reference/cstdio/printf/ – Mr. Branch Mar 18 '16 at 12:41