# Programming C++ Magic Squares

*label*Programming

*timer*Asked: Nov 26th, 2015

*account_balance_wallet*$30

**Question description**

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.

## Tutor Answer

Brown University

1271 Tutors

California Institute of Technology

2131 Tutors

Carnegie Mellon University

982 Tutors

Columbia University

1256 Tutors

Dartmouth University

2113 Tutors

Emory University

2279 Tutors

Harvard University

599 Tutors

Massachusetts Institute of Technology

2319 Tutors

New York University

1645 Tutors

Notre Dam University

1911 Tutors

Oklahoma University

2122 Tutors

Pennsylvania State University

932 Tutors

Princeton University

1211 Tutors

Stanford University

983 Tutors

University of California

1282 Tutors

Oxford University

123 Tutors

Yale University

2325 Tutors