LAB 3 – Multidimensional Arrays (INDIVIDUAL
WORK)
In-lab activity (due at the end of the lab
session)
A magic square is a
grid of numbers where each row, column, and both diagonals have the same
sum. For example, the grid:
8 1 6
3 5 7
4 9 2
is a magic square
because each row, column and diagonal sums to 15.
Complete the magic
square testing program shown below:
#include <iostream>
#include <string>
using namespace std;
const int squareSize = 4;
// Function Prototypes
bool isMagicSquare(int
magicSquare[squareSize][squareSize]);
void printMagicSquare(int
magicSquare[squareSize][squareSize]);
int main()
{
int
firstSquare[squareSize][squareSize] =
{ { 1, 15, 14, 4},
{12,
6, 7, 9},
{ 8, 10, 11, 5},
{13,
3, 2, 16} };
int
secondSquare[squareSize][squareSize] =
{ { 1, 15, 14, 4},
{12,
7, 6, 9},
{ 8, 11, 10, 5},
{13,
3, 2, 16} };
cout
<< endl << "The array: " << endl;
printMagicSquare( firstSquare );
if (
isMagicSquare( firstSquare ) )
{
cout
<< " is a Magic Square." << endl;
}
else
{
cout
<< " is NOT a Magic Square." << endl;
}
cout
<< endl << "The array: " << endl;
printMagicSquare( secondSquare );
if (
isMagicSquare( secondSquare ) )
{
cout
<< " is a Magic Square." << endl;
}
else
{
cout
<< " is NOT a Magic Square." << endl;
}
}
/*
* Check an array of numbers to see if it is a
magic square.
*
* The numbers in the array must sum to the
same number in each
* row, column and both diagonals.
*
* Parameters:
* magicSquare - the array of numbers.
*/
bool isMagicSquare( int
magicSquare[squareSize][squareSize] )
{
//
Calculate the required sum. All the
other rows must have
// this same sum to have a magic square.
int
requiredSum = squareSize * (squareSize * squareSize + 1 ) / 2;
int row =
0;
int column
= 0;
// Check
each row
int rowSum
= 0;
for (row =
0; row < squareSize; row++)
{
// Add
up the current row
rowSum =
0;
for
(column = 0; column < squareSize; column++)
{
rowSum = rowSum + magicSquare[row][column];
}
// Did
we get the same sum as the required sum?
if
(rowSum != requiredSum)
{
return false;
}
}
// Check
each column
int
columnSum = 0;
for (; ;
column++)
{
//
Initialize column sum
// Add
up the current column
// Did
we get the same sum as the required sum?
// If not then return false.
if ( )
{
return false;
}
}
// Sum the
numbers on the first diagonal
// Did we
get the same sum as the required sum?
// If not then return false
// Sum the
numbers on the second diagonal
// Did we
get the same sum as the required sum?
// If not then return false
// This
must be a magic square
return
true;
}
/*
* Print the array of numbers
*
* Parameters:
* magicSquare - the array of numbers.
*/
void printMagicSquare( int
magicSquare[squareSize][squareSize] )
{
int row =
0;
int column
= 0;
for (row =
0; row < squareSize; row++)
{
for
(column = 0; column < squareSize; column++)
{
cout
<< magicSquare[row][column] << " ";
}
cout
<< endl;
}
}