Write a function that returns true if an n x n array is a magic square and false
ID: 3575954 • Letter: W
Question
Write a function that returns true if an n x n array is a magic square and false if it is not.
The function's prototype is
bool magicSquare(int **, int n);
Write a program to test your function.
See problem 8 on page 450 of your text book for the definition of a 3 x 3 magic square. The definition of an n x n magic square is the same - each row, each column, and each diagonal add up to the same number. The number is n x (n x n + 1) / 2
here is my code
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int ** gen2Array(int n);
void randomFillUnique(int **a, int n)
{
int c = 1;
for (int i = 0; i<n; i++) {
for (int j = 0; j<n; j++)
{
a[i][j] = c;
c++;
}
}
}
int main()
{
int n = 7;
int** result = gen2Array(n);
randomFillUnique(result, n);
cout << "Generated array : " << endl;
for (int i = 0; i<n; i++)
{
for (int j = 0; j<n; j++)
{
cout << result[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
int ** gen2Array(int n)
{
int **p;
p = new int*[n];
for (int i = 0; i < n; ++i) {
p[i] = new int[n];
}
return p;
}
Explanation / Answer
Here is the code to check if your square is magic square or not.
bool magicSquare(int **p, int n)
{
int sum = 0;
for(int i = 0; i < n; i++) //For the first row, calculate the sum.
sum += p[0][i];
int temp = 0;
for(int i = 1; i < n; i++) //For each other row, if the sum is not equal to that, return false.
{
temp = 0;
for(int j = 0; j < n; j++)
temp += p[i][j];
if(sum != temp)
return false;
}
for(int i = 0; i < n; i++) //For each column, if the sum is not equal to that, return false.
{
temp = 0;
for(int j = 0; j < n; j++)
temp += p[j][i];
if(temp != sum)
return false;
}
temp = 0;
for(int i = 0; i < n; i++) //For the leading diagonal, if the sum is not equal to that, return false.
temp += p[i][i];
if(temp != sum)
return false;
temp = 0;
for(int i = 0; i < n; i++) //For the trailing diagonal, if the sum is not equal to that, return false.
temp += p[i][n-i-1];
if(temp != sum)
return false;
return true; //If all tests pass, return true.
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.