Home‎ > ‎Assignments‎ > ‎

Magic Square | Solution

(for solution with indenting see pdf)

//Assignment - Magic Square
//simple code version
//author: Professor
//last compiled: March 16, 2015

#include <iostream>
using namespace std;

int const Maxsize=10;

int main(){
int inmatrix[Maxsize][Maxsize]; // array to hold data
int ndim; // dimension
int i,j; // index variables 
int testsum, sum, tempsum;
bool ismagic;

// read size of matrix
cout << "Dimension of data matrix is = "; cin >> ndim;
// read matrix
for (i=0; i<ndim ; i++){
cout << "values in row " << i+1 << " are? " << endl;
for (j=0; j<ndim; j++){ 
cout << "value " << j+1 << "? "; cin >> inmatrix[i][j];
}}

//echo print matrix input
cout << "Your square:\n";
for (i=0; i<ndim ; i++){
for (j=0; j<ndim; j++) 
cout << inmatrix[i][j];
cout << endl;
}

// now test if magic square
// get sum of first row
sum=0;
for (j=0 ; j< ndim ; j++)
sum += inmatrix[0][j]; 
// test rows
ismagic= true;
for (i=1; i< ndim; i++){
tempsum=0;
for (j=0 ; j< ndim ; j++)
tempsum += inmatrix[i][j];
if (tempsum != sum) ismagic=false;
}

// now test cols
for (j=0; i< ndim; j++){
tempsum=0;
for (i=0 ; i< ndim ; i++)
tempsum += inmatrix[i][j];
if (tempsum != sum) ismagic=false;
}

// now diag 1
testsum=0;
for (i=0; i< ndim; i++)
testsum += inmatrix[i][i];
if (testsum != sum)
ismagic=false;

// now diag 2
testsum=0;
for (i=0; i< ndim; i++)
testsum += inmatrix[i][ndim-i-1];
if (testsum != sum)
ismagic=false;

if (ismagic)
cout << "\n Matrix is a magic square \n\n";
else
cout << "\n Matrix is not a magic square \n\n";

return 0;
}

Comments