****Need this in C++**** Magic squares. An n × n matrix that is filled with the
ID: 3902475 • Letter: #
Question
****Need this in C++****
Magic squares. An n × 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 16 3 2 13 5 1011 8 96 7 12 4 15 14 1 Write a program that reads in 16 values from the keyboard and tests whether they form a magic square when put into a 4 x 4 array. You need to test two features 1. Does each of the numbers 1, 2,.,16 occur in the user input? 2. When the numbers are put into a square, are the sums of the rows, columns, and diagonals equal to each other?Explanation / Answer
the code will be
#include <iostream>
using namespace std;
bool check(int **arr)
{
int sum=arr[0][0]+arr[0][1]+arr[0][2]+arr[0][3];
for(int i=1;i<4;i++)
{
int sum1=0;
for(int j=0;j<4;j++)
sum+=arr[i][j];
if(sum1!=sum)return false;
}
for(int i=0;i<4;i++)
{
int sum1=0;
for(int j=0;j<4;j++)
sum+=arr[j][i];
if(sum1!=sum)return false;
}
int sum1=0;
for(int i=0;i<4;i++)sum1+=arr[i][i];
if(sum1!=sum)return false;
if(sum!=arr[3][0]+arr[2][1]+arr[1][2]+arr[0][3])return false;
return true;
}
int main()
{
int arr[4][4];
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++){
int d;
cout<<"Enter a value between 1 and 16(inclusive) ";
cin>>d;
while(!(d<=16 && d>=1))
{
cout<<"Enter the correct value ";
cin>>d;
}
arr[i][j]=d;
}
}
}
Do give a thumbs up and in case there are doubts leave a comment.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.