Question

I need this written in C++. Magic Squares. An n x n matrix that is filled...

I need this written in C++. Magic Squares. An n x n matrix that is filled with the numbers 1,2,3,…,n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value.
The following algorithm will construct magic n x n squares; it only works if n is odd: Place 1 in the middle of the bottom row. After k has been placed in the (i,j) square, place k+1 into the square right and down, wrapping around the borders. However, if you reach a square that has already been filled, then you must move one square up instead.
Here is the 5 x 5 square that you get if you follow this method:

11 18 25 2 9

10 12 19 21 3

4 6 13 20 22

23 5 7 14 16

17 24 1 8 15

Make a function with an array argument that will make a magic square.

Make another function that will check if its array argument is a magic square.

Make a third function that can be passed a matrix of the same size as the magic squares created by your first function, and will allow the user to enter any number of changes the user wants to make to the values of the matrix.

Make a main function that will make a magic square, print it, check if it is a magic square, allow the user to change it, print it again, and check if it is a magic square after the changes.

Also: Define a class MagicSquare, which will store a square matrix in a dynamically allocated two-dimensional array. Create a magic square by the constructor, and provide methods isMagic and setValues corresponding to the second and third functions described above. Provide a main function to test your class as above.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// C++ program to create a class to generate Magic Square and then allow the user to modify the values and then check if it is magic square or not
#include <iostream>

using namespace std;

class MagicSquare
{
private:
int **magic; // dynamic array to store the magic square
int size; // size of the matrix
public:
MagicSquare(int n);
bool isMagic() const;
void setValues();
void display() const;
};

// function declaration
void makeMagicSquare(int **matrix, int size);
bool isMagicSquare(int **matrix, int size);
void makeChanges(int **matrix, int size);
void printMatrix(int **matrix, int size);


int main()
{
const int size = 5;

// create a matrix of size and initialize all elements to 0
int **matrix = new int*[size];
for(int i=0;i<size;i++){
matrix[i] = new int[size];
for(int j=0;j<size;j++)
matrix[i][j] = 0;
}

cout<<"Creating magic square of size "<<size<<" using functions:"<<endl;
makeMagicSquare(matrix, size);
printMatrix(matrix, size);
if(isMagicSquare(matrix,size))
cout<<"MAGIC SQUARE."<<endl;
else
cout<<"NOT A MAGIC SQUARE."<<endl;

cout<<"Make changes to the matrix"<<endl;
makeChanges(matrix, size);
printMatrix(matrix,size);
if(isMagicSquare(matrix,size))
cout<<"MAGIC SQUARE."<<endl;
else
cout<<"NOT A MAGIC SQUARE."<<endl;

cout<<"Creating magic square of size "<<size<<" using class:"<<endl;
MagicSquare magic(5); // generate magic square of size 5
magic.display(); // display the array
// check and display if the matrix is magic square or not
if(magic.isMagic())
cout<<endl<<"The above matrix is a MAGIC SQUARE. "<<endl;
else
cout<<endl<<"The above matrix is not a MAGIC SQUARE. "<<endl;

magic.setValues(); // allow user to update the values
magic.display(); // display the updated array
// check and display if updated matrix is magic square or not
if(magic.isMagic())
cout<<endl<<"The above matrix is a MAGIC SQUARE. "<<endl;
else
cout<<endl<<"The above matrix is not a MAGIC SQUARE. "<<endl;

return 0;
}

// constructor that takes as input the size of the matrix and generate the magic square according to the given algorithm
MagicSquare::MagicSquare(int n)
{
// check if input is odd, then set size to n else by default set n to 5
if(n%2 != 0)
size = n;
else
size = 5;
// create the dynamic array of size*size
magic = new int*[size];
for(int i=0;i<size;i++)
{
magic[i] = new int[size];
for(int j=0;j<size;j++)
{
magic[i][j] = 0; // initialize all entries to 0
}
}

// populate the matrix according to the algorithm
int row=size-1; // set row to last row
   int col=size/2; // set col to middle column

   // loop size*size times
   for(int cnt = 1;cnt<=size*size;)
   {
   // if location (row,col) is filled, then move one square up
   if(magic[row][col] != 0)
{
row--;
if(row == -1) // if row reached outside matrix, then wrap around
row = size-1;
row--;
   if(row == -1)
       row = size-1;
col--;
if(col == -1) // if col reached outside matrix, then wrap around
col = size-1;
continue;
}
   else // if not filled, populate the location with cnt and increment cnt
magic[row][col] = cnt++;

// move into square right and down
row++;
   if(row == size) // if row reached outside matrix, then wrap around
row = 0;
   col++;

   if(col == size) // if col reached outside matrix, then wrap around
col = 0;
   }
}

// function to check and return if the matrix is a magic square or not
bool MagicSquare:: isMagic() const
{
int sum = 0, rowSum, colSum;
// calculate the sum of first row
for(int i=0;i<size;i++)
sum += magic[0][i];

// loop to calculate row sum and column sum
for(int i=0;i<size;i++)
{
rowSum = 0 ;
colSum = 0;
for(int j=0;j<size;j++)
{
rowSum += magic[i][j];
colSum += magic[j][i];
}

// check if sum of ith row and ith column is equal to sum
if((rowSum != sum) || (colSum != sum))
return false; // if not return false
}

// calculate main diagonal sum

int diagonalSum = 0;
for(int i=0;i<size;i++)
diagonalSum += magic[i][i];

if(diagonalSum != sum) // check diagonal sum = sum
return false;

// calculate other diagonal sum
diagonalSum = 0;

for(int i=0;i<size;i++)
diagonalSum += magic[i][size-1-i];
// check other diagonal sum = sum
if(diagonalSum != sum)
return false;

return true; // it is a magic square

}

// function to display the matrix
void MagicSquare:: display() const
{
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
cout<<magic[i][j]<<" ";
cout<<endl;
}
}

// function to allow user to modify the values of the matrix
void MagicSquare:: setValues()
{
int row, col, value;
char choice;

// loop till the user wants
do
{
// input the row and column of matrix which needs to be changed
cout<<"Enter row(1-"<<size<<") and column(1-"<<size<<") for the element to change (separated by a space): ";
cin>>row>>col;
// input the value to set
cout<<"Enter the value to set: ";
cin>>value;
// update the value at given position
magic[row-1][col-1] = value;

// ask if user wants to change more
cout<<"Do you want to make more changes? (y/n) ";
cin>>choice;
}while(choice == 'y' || choice == 'Y');
}


// function to create a magic square of size where size is odd
void makeMagicSquare(int **matrix, int size)
{
int row=size-1; // set row to last row
   int col=size/2; // set col to middle column

   // loop size*size times
   for(int cnt = 1;cnt<=size*size;)
   {
   // if location (row,col) is filled, then move one square up
   if(matrix[row][col] != 0)
{
row--;
if(row == -1) // if row reached outside matrix, then wrap around
row = size-1;
row--;
   if(row == -1)
       row = size-1;
col--;
if(col == -1) // if col reached outside matrix, then wrap around
col = size-1;
continue;
}
   else // if not filled, populate the location with cnt and increment cnt
matrix[row][col] = cnt++;

// move into square right and down
row++;
   if(row == size) // if row reached outside matrix, then wrap around
row = 0;
   col++;

   if(col == size) // if col reached outside matrix, then wrap around
col = 0;
   }
}

// function to return true if input matrix of size is magic square otherwise return false
bool isMagicSquare(int **matrix, int size)
{
int sum = 0, rowSum, colSum;
// calculate the sum of first row
for(int i=0;i<size;i++)
sum += matrix[0][i];

// loop to calculate row sum and column sum
for(int i=0;i<size;i++)
{
rowSum = 0 ;
colSum = 0;
for(int j=0;j<size;j++)
{
rowSum += matrix[i][j];
colSum += matrix[j][i];
}

// check if sum of ith row and ith column is equal to sum
if((rowSum != sum) || (colSum != sum))
return false; // if not return false
}

// calculate main diagonal sum

int diagonalSum = 0;
for(int i=0;i<size;i++)
diagonalSum += matrix[i][i];

if(diagonalSum != sum) // check diagonal sum = sum
return false;

// calculate other diagonal sum
diagonalSum = 0;

for(int i=0;i<size;i++)
diagonalSum += matrix[i][size-1-i];
// check other diagonal sum = sum
if(diagonalSum != sum)
return false;

return true; // it is a magic square

}

// function to allow the user to make changes to the input matrix of size by the user.
void makeChanges(int **matrix, int size)
{
int row, col, value;
char choice;

// loop till the user wants
do
{
// input the row and column of matrix which needs to be changed
cout<<"Enter row(1-"<<size<<") and column(1-"<<size<<") for the element to change (separated by a space): ";
cin>>row>>col;
// input the value to set
cout<<"Enter the value to set: ";
cin>>value;
// update the value at given position
matrix[row-1][col-1] = value;

// ask if user wants to change more
cout<<"Do you want to make more changes? (y/n) ";
cin>>choice;
}while(choice == 'y' || choice == 'Y');

}

// function to display the matrix of size
void printMatrix(int **matrix, int size)
{
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
cout<<matrix[i][j]<<" ";
cout<<endl;
}
}

//end of program

Output:

Creating magic square of size 5 using functions: 11 18 25 2 9 10 12 19 21 3 4 6 13 20 22 23 5 7 14 16 17 24 1 8 15 MAGIC SQUA

Add a comment
Know the answer?
Add Answer to:
I need this written in C++. Magic Squares. An n x n matrix that is filled...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ Magic Squares. An n x n matrix that is filled with the numbers 1,2,3,…,n2 is...

    C++ Magic Squares. An n x n matrix that is filled with the numbers 1,2,3,…,n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value. The following algorithm will construct magic n x n squares; it only works if n is odd: Place 1 in the middle of the bottom row. After k has been placed in the (i,j) square, place k+1 into the square...

  • Magic Squares; Java code

    Magic squares. An n × n matrix that is filled with the numbers 1, 2, 3, ..., n2 is a magic square if the sum ofthe elements in each row, in each column, and in the two diagonals is the same value. For example,16 3 2 135 10 11 89 6 7 124 15 14 1Write a program that reads in n2 values from the keyboard and tests whether they form a magic squarewhen arranged as a square matrix. You...

  • Java Magic Square: A n x n matrix that is filled with the numbers 1, 2,...

    Java Magic Square: A n x n matrix that is filled with the numbers 1, 2, 3,.... n^2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value. I need to write an application that gets 16 values as user input, in any order. Store these values in an ArrayList. When the numbers are put into a square, this would be a 4x4 two-dimensional array....

  • Write C++ programs that create TEN(10) different N*N magic squares. A square matrix is the arrangement...

    Write C++ programs that create TEN(10) different N*N magic squares. A square matrix is the arrangement of the numbers 1, 2, ., N2, in which the sum of rows, columns, and diagonals are the same. The users (i.e., TAs) will specify the size of the square matrix: N. The value N must be an odd number between 3 and 15. Example Run For example, you program is expected to run as the following way. NOTE: We only list 5 magic...

  • 8. Ann x n matrix that is filled with the numbers 1,2,3, ....n2 is a magic...

    8. Ann x n matrix that is filled with the numbers 1,2,3, ....n2 is a magic square if the sum of the elements in each row, in each column, and in the two main diagonals is the same value. For example, 16 3 213 5 10 11 8 9 6 7 12 4 15 14 1 Write the program that reads in 16 values from the keyboard and tests whether they form a magic square when put into a 4...

  • This assignment requires you to write a program to implement an odd-order Magic Square. Prompt the...

    This assignment requires you to write a program to implement an odd-order Magic Square. Prompt the user to enter the “order” of the square and then produce for the user a magic square of that order. Run your code for at least four different inputs – all odd. ODD ORDER MAGIC SQUARES 1. Start by placing 1 in the middle column of the top row. 2. Continue by always placing the next number (say k+1) in the square diagonally up...

  • I need help as quick as possible, thanks beforehand. Please provide the test output The Lo...

    I need help as quick as possible, thanks beforehand. Please provide the test output The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown below. 35 The Lo Shu Magic Square has the following properties: The grid contains the numbers 1 - 9 exactly The sum of each row, each column and each diagonal all add up to the same number. This is shown below: 15 4 92 15 - 81 + 15 15 15...

  • Use basic java for this after importing PrintWriter object You will make a simple Magic Square...

    Use basic java for this after importing PrintWriter object You will make a simple Magic Square program for this Java Programming Assignment. Carefully read all the instructions before beginning to code. It is also required to turn in your pseudocode or a flowchart along with this program. Here are the instructions: At the beginning of the program, briefly describe to the user what a Magic Square Matrix is (described further on), and then allow them to enter “start” to begin...

  • I am using C++ Write a program to determine if a gird follows the rules to...

    I am using C++ Write a program to determine if a gird follows the rules to be classified as a Lo Shu Magic Square. The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown in figure below. The Lo Shu Magic Square has the following properties: The grid contains the numbers 1 through 9 exactly. The sum of each row, each column, and each diagonal all add up to the same number. This is shown...

  • C++ Lab 11 – Is This Box a Magic Box? Objectives: Define a two dimensional array Understand h...

    C++ Lab 11 – Is This Box a Magic Box? Objectives: Define a two dimensional array Understand how to traverse a two dimensional array Code and run a program that processes a two dimensional array Instructions: A magic square is a matrix (two dimensional arrays) in which the sum of each row, sum of each column, sum of the main diagonal, and sum of the reverse diagonal are all the same value. You are to code a program to determine...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT