My assignment is to make a magic square based on an odd integer entered by the user. The number entered is the order of this "magic" square. The reason this square is magic is because all rows and columns of the square are supposed to sum to 15. When I build the code it says there is no errors. However I try and run and my machine stops responding. Was wondering if someone could point out what I did wrong..
The algorithm for filling the square.
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:
a) 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.
b) 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.
c) 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’
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
|
#include<iostream>
using namespace std;
int main()
{
int order;
int MagicArray[order][order];
int Row,Col;
//Menu, User oicks order of square
cout<<"Welcome to my magic square program!"<<endl;
cout<<"Please enter the order of the Magic Square (Note-must be odd):";
A:
cin>>order;
//Checks if number is odd
if (order % 2 == 0)
{
cout<<"Entry was not odd, please enter odd number:";
goto A;
}
//Start by placing 1 in top row middle column
Row = 0;
Col = order/2;
// rest of Algorithm for filling in Magic Square
for (int currNumb = 1; currNumb <= order*order; currNumb++)
{
MagicArray[Row][Col] = currNumb;
Row--;
Col++;
//If new space is filled or off in very right corner, next space underneath last entry
if((Row<0 && Col==order)||(MagicArray[Row][Col]!= 0))
{
Row++;
Col--;
Row++;
}
//If new space is above maxtrix, new space very bottom of same column
else if(Row<0)
Row = order - 1;
//If new space is to the right of matrix, new space is very left of same row
else if(Col==order)
Col = 0;
}
//Prints the magic Square
for(Row=0;Row<order;Row++){
for(Col=0; Col<order;Col++){
cout<<MagicArray[Row][Col]<<endl;
}
}
}
|