Im using visual c++ 2008 express edition from microsoft
Write a program that reads in 16 values from the keyboard and tests whether they form a magic square when put into a 4x4 array. You need to rest two features :
-does each of the numbers 1,2,...,16 occur in the user input
-When the numbers are put into a square, are the sums of the rows, columns, and diagonals equal to eachother?
a magic square is when the sum of the elements in each row, column and in the two diagonals have the same value.
Well, I'm still learning myself - but maybe to get you started:
using namespace std;
int magic_square[4][4];
int sum_rows[4] = {0, 0, 0, 0};
int sum_cols[4] = {0, 0, 0, 0};
int sum_diags[2] = {0, 0};
cout << "Please enter 16 numbers:\n";
// Collect user input
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
while(!(cin >> magic_square[row][col])) {
cin.clear();
cin.ignore(10000, '\n');
cout << "! Not a number, please try again:";
}
}
}
// Display 4x4 table
cout << "\nHere is the table:\n";
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
cout << setw(8) << left << magic_square[row][col];
}
cout << "\n";
}
// Sum of rows and columns
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
sum_rows[i] += magic_square[i][j];
sum_cols[i] += magic_square[j][i];
}
}
// Sum of diagonal from [0][0] to [3][3]
for (int i = 0; i < 4; i++)
sum_diags[0] += magic_square[i][i];
// Sum of diagonal from [0][3] to [3][0]
for (int i = 3, j = 0; i >= 0; i--, j++)
sum_diags[1] += magic_square[i][j];
// And... I'm too lazy to write something that compares all the values