Write a C++ program that asks the user to enter the numbers 1 to 16 (in any orde
ID: 3665364 • Letter: W
Question
Write a C++ program that asks the user to enter the numbers 1 to 16 (in any order) and then displays the numbers in a 4 x 4 aligned arrangement, followed by the sums of the rows, columns, and diagonals. A session of the program will look like
Enter the numbers from 1 to 16 in any order:
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
The 4 x 4 arrangement is
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Row sums: 34 34 34 34
Column sums 34 34 34 34
Diagonal sums: 34 34
Note: If the row, column, and diagonal sums are all the same, the numbers are said to form a magic square.
Hint: use setw function to specify field width. Look online to find the library that is required for this function.
Explanation / Answer
#include <iostream>
#include <iomanip>
using namespace std;
void magic(int a[4][4])//To find whether the values form magic square or not
{
//For diagonal elements
int sum = 0,row,column,size=4,flag=0;
for ( row = 0; row < size; row++) {
for (column = 0; column < size; column++) {
if (row == column)
sum = sum + a[row][column];
}
}
//For Rows
for (row = 0; row < size; row++) {
int sum1 = 0;
for (column = 0; column < size; column++) {
sum1 = sum1 + a[row][column];
}
if (sum == sum1)
flag = 1;
else {
flag = 0;
break;
}
}
//For Columns
for (row = 0; row < size; row++) {
int sum2 = 0;
for (column = 0; column < size; column++) {
sum2 = sum2 + a[column][row];
}
if (sum == sum2)
flag = 1;
else {
flag = 0;
break;
}
}
if (flag == 1)
cout<<" Magic square";
else
cout<<" No Magic square";
}
int main()
{
int a[4][4],b[16],i,j,k,sum;
cout<<" Enter the 16 values between 1-16 in any order ";
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
cout<<setw(4)<<a[i][j];
}
cout<<" ";
}
for(i=0; i<4; i++)
{
sum = 0;
for(j=0; j<4; j++)
{
sum += a[i][j];
}
cout<<" Sum of elements of Row "<<i+1<< "="<<sum ;
}
for(i=0; i<4; i++)
{
sum = 0;
for(j=0; j<4; j++)
{
sum += a[j][i];
}
cout<<" Sum of elements of column "<<i+1<< "="<<sum ;
}
sum = 0;
int sum1=0;
for (i = 0; i < 4; ++i)
{
sum = sum + a[i][i];
sum1 = sum1+ a[i][4 - i - 1];
}
cout<<" The sum of the main diagonal elements is =" <<sum;
cout<<" The sum of the off diagonal elemets is ="<< sum1;
magic(a);
}
Magic function is created for find wheather the given values form magic square or not
If you have any doubts regarding this program i will clarify to you
Thank u...
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.