Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple C++ program which checks whether a three by three array of numbers is a magic square.
#include <iostream>
using namespace std;
// prototype
bool isMagicSquare(int[][3]);
int sumRow(int[], int);
int sumColumn(int[][3], int);
int sumDiagonal1(int[][3]);
int sumDiagonal2(int[][3]);
int main() {
int square[][3] = {{2,7,6},
{9,5,1},
{4,3,8}};
cout << isMagicSquare(square) << endl;
return 0;
}
bool isMagicSquare(int square[3][3]) {
int rowSum = 0,
columnSum = 0,
diagonalSum1 = 0,
diagonalSum2 = 0;
// check rows
for (int i = 0; i < 3; i++) {
rowSum = sumRow(square[i], 3);
if (rowSum != 15) {
cout << "Returning false at row." << endl;
return false;
}
}
// check columns
for (int i = 0; i < 3; i++) {
columnSum = sumColumn(square, i);
if (columnSum != 15) {
cout << "Returning false at column." << endl;
return false;
}
}
diagonalSum1 = sumDiagonal1(square);
diagonalSum2 = sumDiagonal2(square);
if (diagonalSum1 != 15 || diagonalSum2 != 15) {
cout << "Returning false at diagonal." << endl;
return false;
}
return true;
}
int sumRow(int row[], int size) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += row[i];
}
return sum;
}
int sumColumn(int square[][3], int column) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += square[i][column];
}
return sum;
}
// sums the diagonal from upper-left corner to lower-right corner
int sumDiagonal1(int square[][3]) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += square[i][i];
}
return sum;
}
// sums the diagonal from upper-right corner to lower-left corner
int sumDiagonal2(int square[][3]) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += square[i][2 - i];
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.