Always comes back as magic
Nov 20, 2014 at 3:16am UTC
I'm not quite sure what went wrong, but after i modified this so the user input is stored into an array everything comes back as a magic square. Before i was just going to have everything be calculated in different functions but decided against it which is why the global variables exist.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include<iostream>
using namespace std;
// global variables
const int ROWS = 4;
const int COLUMNS = 4;
int main() {
//initialize variables
int input;
int sum0, sum1, sum2, sum3;
int vsum0, vsum1, vsum2, vsum3;
int dsum1, dsum2;
// initialize array
int numbers[ROWS][COLUMNS] = {0};
//Welcome and Prompt
cout << "Welcome to Tali's Magic Square Checker! Please enter your magic square:" << endl;
// save input in an array
for (int i = 0; i < ROWS; i++){
// Get user input
for ( int j = 0; j < COLUMNS; j++){
// get input
cin >> input;
numbers[i][j];
}
}
// calculate horizontal sum
sum0 = numbers[0][0]+ numbers[0][1] + numbers[0][2] + numbers[0][3];
sum1 = numbers[1][0]+ numbers[1][1] + numbers[1][2] + numbers[1][3];
sum2 = numbers[2][0]+ numbers[2][1] + numbers[2][2] + numbers[2][3];
sum3 = numbers[3][0]+ numbers[3][1] + numbers[3][2] + numbers[3][3];
// calculate vertical sum
vsum0 = numbers[0][0]+ numbers[1][0] + numbers[2][0] + numbers[3][0];
vsum1 = numbers[0][1]+ numbers[1][1] + numbers[2][1] + numbers[3][1];
vsum2 = numbers[0][1]+ numbers[1][2] + numbers[2][2] + numbers[3][2];
vsum3 = numbers[0][3]+ numbers[1][3] + numbers[2][3] + numbers[3][3];
// calculate diag sum
dsum1 = numbers[0][0]+ numbers[1][1] + numbers[2][2] + numbers[3][3];
dsum2 = numbers[3][0]+ numbers[2][1] + numbers[1][2] + numbers[0][3];
if ( sum0 == sum1 && sum1 == sum2 && sum2 == sum3
&& sum3 == vsum0 && vsum0 == vsum1 && vsum1 == vsum2
&& vsum2 == vsum3 && vsum3 == dsum1 && dsum1 == dsum2 && dsum2 == sum0){
cout << "This was a magic square! Thank you!" ;}
// If it isn't a magic sqaure, output this
else if ( sum0 != dsum2)
{cout << "This was not a magic square! Thank you!" ;
}
//pause and exit
getchar();
getchar();
return 0;
}
Nov 20, 2014 at 3:20am UTC
you intialize your array with the value of 0 (line 16), but you never sore user input in array indexes (check lines 26, 27). Since every index is zero, every value is equal, therefore it's always a magic square.
Nov 20, 2014 at 3:24am UTC
Ah! Thank you. I totally forgot about that.
Topic archived. No new replies allowed.