C++ only Magic Squares: An n x n array, that is filled with integers 1, 2, 3, …,
ID: 3696201 • Letter: C
Question
C++ only
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.
2
7
6
9
5
1
4
3
8
Explanation / Answer
#include<stdio.h>
#include<conio.h>
int main() {
int size = 3;
int matrix[3][3]; // = {{4,9,2},{3,5,7},{8,1,6}};
int row, column = 0;
int sum, sum1, sum2;
int flag = 0;
printf(" Enter matrix : ");
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++)
scanf("%d", &matrix[row][column]);
}
printf("Entered matrix is : ");
for (row = 0; row < size; row++) {
printf(" ");
for (column = 0; column < size; column++) {
printf(" %d", matrix[row][column]);
}
}
//For diagonal elements
sum = 0;
for (row = 0; row < size; row++) {
for (column = 0; column < size; column++) {
if (row == column)
sum = sum + matrix[row][column];
}
}
//For Rows
for (row = 0; row < size; row++) {
sum1 = 0;
for (column = 0; column < size; column++) {
sum1 = sum1 + matrix[row][column];
}
if (sum == sum1)
flag = 1;
else {
flag = 0;
break;
}
}
//For Columns
for (row = 0; row < size; row++) {
sum2 = 0;
for (column = 0; column < size; column++) {
sum2 = sum2 + matrix[column][row];
}
if (sum == sum2)
flag = 1;
else {
flag = 0;
break;
}
}
if (flag == 1)
printf(" Magic square");
else
printf(" No Magic square");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.