I cannot understand why it doesnt fill the array the way it supposed to.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int number;
printf("Type an odd number between 3 and 9:");
while(!(number % 2)){//Odd control
scanf("%d" , &number);
if(!(number % 2))printf("\nYou didnt type an odd number, please type again:");
}
//array
int magicsquare[number][number];
memset(magicsquare, 0, sizeof(magicsquare));
int i,j;
//putting the one
int one = (number+1) /2 ;
printf("%d", one);
magicsquare[ one - 1 ][ number - 1 ] = 1;
//filling the array
int counter = 0, limit = number - 1, fill = 2, tempj = 0;
i = one - 1;
j = limit ;
while ( fill <= (number*number)){
i = i + 1;
if ( i > limit) {
i = 0 ;
counter++;
}
tempj = j;//it keeps the j in case the i,j goes out
j = j + 1;
if ( j > limit ){
j = 0;
counter++;
}
if ( counter == 2){//when i and j goes beyond the array
magicsquare[i][tempj] = fill;
fill++;
}
else{
if ( magicsquare[i][j] == 0){
magicsquare[i][j] = fill;
fill++;
}
else {
i = i - 1;
j = j - 2;
magicsquare[i][j] = fill;
fill++;
}
}
printf("\ncounter=%d j=%d i=%d fill=%d\n", counter, j, i, fill);
counter = 0;
}
//printing the array
printf("\n");
for(i= 0; i < number ; i++){
for(j =0; j < number; j++){
printf("%d |", magicsquare[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT FOR A 5X5 MAGICSQUARE
11 |10 |4 |23 |16 |
18 |12 |6 |5 |24 |
25 |19 |13 |7 |1 |
2 |0 |20 |14 |8 |
9 |3 |0 |21 |15 |
WHEN 5X5 SQUARE IT SHOULD BE LIKE THIS:
11 10 4 23 17
18 12 6 5 24
25 19 13 7 1
2 21 20 14 8
9 3 22 16 15