This assignment requires you to write a program to implement an odd-order Magic
ID: 3668457 • Letter: T
Question
This assignment requires you to write a program to implement an odd-order Magic Square. Prompt the user to enter the “order” of the square and then produce for the user a magic square of that order. Run your code for at least four different inputs – all odd.
ODD ORDER MAGIC SQUARES
1. Start by placing 1 in the middle column of the top row.
2. Continue by always placing the next number (say k+1) in the square diagonally up and to the right.
Example: if integer ‘k’ was placed in position [row][col], then integer ‘k+1’ should be positioned in [row-1][col+1], unless one of the following occurs:
If a move takes you above the top row in the jth column, move to the bottom of the jth column and place ‘k+1’ there.
If a move takes you outside to the right of the square in the ith row, place ‘k+1’ in the i-th row at the left side.
If a move takes you to an already filled square of if you move out of the square at the upper right hand corner, place ‘k+1’ immediately below ‘k’
You might want to consider the following:
Allocating new chunk of memory based on the order which the user enters
Having a “print” function to print out the magic square
Using commands like setw() to format your output
Check to see if the user input is valid (i.e. an odd number)
Score for correct output for your inputs (4 different ones)
Is there a limit to the order of the square
Explanation / Answer
#include <iostream>
#include <iomanip>
using namespace std;
main () {
//This will ask for user input and
//verify that it is a valid input.
int order;
cout << "Magic Square Generator " << "===================== ";
cout << "Enter Order of square: ";
cin >> order;
if(order==1 | order%2==0) {
cout << "Invalid number, please enter an odd number greater than 1. ";
return 0;
}
//This will initialize the square, zeroing out the elements.
int square[order][order];
for(int i=0; i<order; i++)
for(int n=0; n<order; n++)
square[i][n] = 0;
square[0][order/2] = 1;
int nextRow = -1;
int nextColumn = (order/2)+1;
//This will populate the array,
//while also checking for special cases and adjusting.
for(int nextInt=2; nextInt<=(order*order); nextInt++) {
if(nextColumn>=order && nextRow<0) {
nextColumn -= 1;
nextRow += 2;
}
if(nextColumn>=order)
nextColumn = 0;
if(nextRow<0)
nextRow = order-1;
if(square[nextRow][nextColumn]!=0) {
nextColumn -= 1;
nextRow +=2;
}
square[nextRow][nextColumn] = nextInt;
nextRow--;
nextColumn++;
}
//This prints the array once the generation is complete.
for(int i=0; i<order; i++) {
for(int n=0; n<order; n++) {
cout << setw(5);
cout << square[i][n];
}
cout << endl;
}
} //End main
sample output
Magic Square Generator
=====================
Enter Order of square: 2
Invalid number, please enter an odd number greater than 1.
Magic Square Generator
=====================
Enter Order of square: 3
8 1 6
3 5 7
4 9 2