output issue please help

This is for a beginner computer science class.

The prompt wants the matrix to have the 1 in the bottom center like this
11 18 25 2 9
10 12 19 21 3
4 6 13 20 22
23 5 7 14 16
17 24 1 8 15


, however for some reason the code shows it in the top center for a sample 5*5 magic square like this,
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Is there anyone out there who knows how to get the magic square to be with the one on the bottom. I know it seems tedious, but its what the assignment requires in order to get a passing grade on it.

Any help would be very much appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
  #include<iostream>
using namespace std;

class MagicSquare {
public:
MagicSquare(int n)
{
    num = n;
    magicSquare = new int* [num];
    for(int i = 0; i < num; i++)
    {
        magicSquare[i] = new int[num];
    }
}
void printMagicSquare(void)
{

    for(int row = 0; row < num; row++)
    {
        for(int col = 0; col < num; col++)
        {
            cout << "\t" << magicSquare[row][col];
        }
    cout << endl;
    }
}
void getRowAndColumn(int& row, int& col, const int counter)
{
  if(counter == 1) { col = num / 2; return;} // Initial condition to insert 0
    else if(row == 0 && (col == num / 2)) { row = num - 1; col++; return;}
    else if(col+1 == num && row == 0) { row++; return;}
    else if(col+1 == num) { col = 0; row--; return;}
    else if(row == 0) { row = num -1; col++; return;}
    else if((row!=0) && (col!=num-1) && magicSquare[row-1][col+1] != 0) { row++; return;}
    else { row--; col++; return;}
}
void computeMagicSquare(void)
{

    int counter  = 1;
    int row = 0;
    int col = 0;
    while(counter <= num*num)
    {
        getRowAndColumn(row, col, counter);
        if(row < 0 || row >= num || col < 0 || col >= num) cout << "Error in calculating Row/Column" << endl << "Row = " << row <<  endl << "Column = " << col << endl;
        magicSquare[row][col] = counter++;
    }
    cout << "\nPrinting magicSquare: " << num << "*" << num << endl;
    printMagicSquare();
}
private:
int **magicSquare;
int num;
};
int main()
{
int num = 0;
cout << "Enter any odd number: ";
cin >> num;
if(num % 2 == 0) {
    cout << "Even number not supported!! " << endl;
    return 1;
}
MagicSquare mSq(num);
mSq.computeMagicSquare();
return 0;
}
Last edited on
Topic archived. No new replies allowed.