Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

In C++ Write a program that will take a 3x3 matrix and test to see if it is a magic square. A 3x3 matrix is

In C++ Write a program that will take a 3x3 matrix and test to see if it is a magic square. A 3x3 matrix is magic if all of the following sums are the same: each row, each column, and both diagonals.

The following example is a magic square because everything adds up to the same number (2+7+6=15, 9+5+1=15, 4+3+8=15, 2+9+4=15, 7+5+3=15, 6+1+8=15, 2+5+8=15, and 4+5+6=15).

2

7

6

9

5

1

4

3

8

Use functions dont put everything in main

Use loops to calculate the sums dont hardcode the calculation. For example, you dont want something like sum = matrix[0][0] + matrix[0][1] + matrix[0][2]. That is hard to update if we change the size of the array

This is what I have so far.

#include

#include

using namespace std;

int row,col;

int matrix;

Int magic;

int main()

{

int matrix[3][3];

int T,D;

cout<<"Enter the elements: ";

for(T=0;D<3;i++)

{

for(T=0;D<3;D++)

{

cin>>matrix[T][D];

}

}

Magic=checkMatrix(matrix);

if(Magic==true)

{

cout<<"Magic";

}

else

{

cout<<"Not Magic";

}

}

int row1=0,row2=0,row3=0,col1=0,col2=0,col3=0,dig1=0,dig2=0;

for(row=0;row<3;row++)

{

for(col=0;col<3;col++)

{

if(row==0)

{

row1 +=matrix[row][col];

}

if(row==1)

{

row2 +=matrix[row][col];

}

if(row==2)

{

row3 +=matrix[row][col];

}

if(col==0)

{

col1 +=matrix[row][col];

}

if(col==1)

{

col2 +=matrix[row][col];

}

if(col==2)

{

col3 +=matrix[row][col];

}

if(row==col)

{

dig1 +=matrix[row][col];

}

if(row+col==2)

{

dig2 +=matrix[row][col];

}

}

}

if(row1==row2 && row1==row3 && row1==col1 && row1==col2 && row1&&col3 && row1==dig1 && row1&&dig2)

{

return true;

}

else{

return false;

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Database Management

Authors: Heikki Topi, Jeffrey A Hoffer, Ramesh Venkataraman

13th Edition

0134773659, 978-0134773650

More Books

Students also viewed these Databases questions

Question

If ( A^2 - A + I = 0 ), then inverse of matrix ( A ) is?

Answered: 1 week ago

Question

What is computer neworking ?

Answered: 1 week ago