Question: I am working on a task with these instructions: Write a program that queries the user for an odd integer n, where n is a
I am working on a task with these instructions:
Write a program that queries the user for an odd integer n, where n is a 3, a 5, or a 7. Create a 7x7 static matrix and use it to produce an n x n magic square as described in the problem.
The problem is that the Magic Square is going above the number 7; it will take any number for some reason when the user inputs it. I need it to be a 7x7 static matrix, as described in the problem.
Please fix my code and comment where you fixed it so I can learn from my mistake.
Here is my code:
```
/*--------------------------------------------------------------------
Program to construct magic squares of odd size.
Input: Size of square (odd #)
Output: A magic square
----------------------------------------------------------------------*/
#include
#include
#include
using namespace std;
const int MAX_DIM = 21;
typedef int IntTable[MAX_DIM][MAX_DIM ];
void createMagic(IntTable square, int n);
/*---------------------------------------------------------------------
Construct a magic square of odd size n.
Precondition: size of square is odd positive integer.
Postcondition: square stores an n x n magic square.
----------------------------------------------------------------------*/
void display(IntTable t, int n);
/*---------------------------------------------------------------------
Display an n x n magic square.
Precondition: None.
Postcondition: square is output to cout.
----------------------------------------------------------------------*/
int main()
{
IntTable square;
int sizeOfSquare;
cout << " Enter size of magic square (odd number): ";
cin >> sizeOfSquare;
createMagic(square, sizeOfSquare);
display(square, sizeOfSquare);
}
//--- Definition of createMagic()
void createMagic(IntTable square, int n)
{
if (n % 2 == 0)
{
cerr << "Size of magic square must be odd. ";
exit(1);
}
int row,
col;
for (row = 0; row < n; row++)
for (col = 0; col < n; col++)
square[row][col] = 0;
row = 0;
col = n / 2;
for (int k = 1; k <= n * n; k++)
{
square[row][col] = k;
row--;
col++;
if (row < 0 && col >= n)
{
row += 2;
col--;
}
if (row < 0)
row = n - 1;
if (col >= n)
col = 0;
if (square[row][col] != 0)
{
row += 2;
col--;
}
}
}
//--- Definition of display()
void display(IntTable t, int n)
{
const int WIDTH = 4;
cout << " Magic square is: " << endl;
for (int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
cout << setw(WIDTH) << t[i][j];
cout << endl << endl;
}
}
```
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
