I've been having a problem with this magic square code for quite some time now. I've just been following a book's algorithm step by step but for some reasons it doesn't display it correctly.
int main(){
    int n;
    char temp[100];
    cout << "Enter an odd number: ";
    cin >> temp;
    n = atoi(temp);
    cout << endl;
    //error if its even
    if (n%2 == 0){
        cout << "Input Error!";
        return (-1);
        cout << endl;
    }
    int square[n][n];
    //places 0 inside
    for (int r = 0; r < n; r++){
        for (int c = 0; c < n; c++){
            square[r][c] = 0;
        }
    }
    //store 1 in middle of first row
    square[0][(n-1)/2] = 1;
    //current position
    int key = 2, i = 0, j = (n-1)/2;
    while(key <= n*n){
        int k = (i-1)%n, l = (j-1)%n; //look up and left
        //square occupied, move down
        if (square[k][l] != 0){
            i = (i+1)%n;
        }
        //square (k,l) needs to be assigned
        else{
            i = k;
            j = l;
        }
        square[i][j] = key; //assign it a value
        key++;
    }
    //display
    for (int r = 0; r < n; r++){
        for (int c = 0; c < n; c++){
            cout << setw(5) << square[r][c] << setw(5);
        }
        cout << endl;
    }
    return 0;
}
If I input 5 as an odd number, the display would be like this:
Enter an odd number: 5
    5   14   22   20   18
    6   15   23    0   19
   17   16   24    0    0
    0    0   25    0    0
    0    0    0    0    0
The output I'm expecting is:
Enter an odd number: 5
   15    8    1   24   17
   16   14    7    5   23
   22   20   13    6    4
    3   21   19   12   10
    9    2   25   18   11
What seems to be the problem?
 
     
     
    