Programming C++ Magic Squares
Magic Squares: An n x n array, that is filled with integers 1, 2, 3, …,n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value (see the magic square below).
|
2 |
7 |
6 |
|
9 |
5 |
1 |
|
4 |
3 |
8 |
Write a program that generates a magic square for an array of size 3 * 3.
Please follow the given steps:
1. Declare a 2D array of 3 * 3.
2. Fill the array with unique values (1-9) generated randomly:
a. Generate a random number in the range of 1-9
b. Check if the random number generated has been previously generated in the array (check if is unique or not)
c. If the number is unique, store it in your 2D array.
3. Display the 2D array
4. Check if the 2D array is a magic square:
i.e: sum of each row = sum of each col = sum of each diagonal 5. Keep repeating (looping) steps 1 to 4 till magic square found.
Sample Output:
1 2 3
4 5 6
7 8 9
Not a Magic Square !
2 3 1
4 5 6
7 8 9
Not a Magic Square !
2 7 6
9 5 1
4 3 8
Magic Square !
Please make sure your code has following functions: 1. checkUnique(): Function to check if the random number generated is a unique number, i.e if the number is not previously generated number in your 2D array. 2. magicSquare(): Function to check if the 2D array is a magic square. Check if sum of each row, sum of each column a sum each diagonal are equal. You can use additional functions (optional) for other operations. Make sure your program runs till the magic square is found.
"You need a similar assignment done from scratch? Our qualified writers will help you with a guaranteed AI-free & plagiarism-free A+ quality paper, Confidentiality, Timely delivery & Livechat/phone Support.
Discount Code: CIPD30
Click ORDER NOW..


