2) Write a program square.c that asks the user to enter the number from 1 to 16
ID: 3738914 • Letter: 2
Question
2) Write a program square.c that asks the user to enter the number from 1 to 16 (in any order) and then displays the numbers in a 4 by 4 arrangement, followed by the sums of the rows, columns, and diagonals: Enter the numbers from 1 to 16 in any order: 163 2 135 10 11 8967 12 4 15_141 16 3 2 13 5 10 118 9 6 712 4 15 141 Row sums: 34 34 34 34 Column sums: 34 34 34 34 Diagonal sums: 34 34 If the row, column, and diagonal sums are all the same (as they are in this example), the numbers are said to form a magic square. The magic square shown here appears in a 1514 engraving by artist and mathematician Albrecht Durer. (Note that the middle numbers in the last row give the date of the engraving.)Explanation / Answer
#include<stdio.h>
int main()
{
int i,j,arr[4][4],row[4] ={0},col[4] ={0},dia1 =0,dia2=0,k=0,flag=0;
printf("Enter elements of the matrix: ");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("Elements of the matrix are: ");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("%d ",arr[i][j]);
row[i]=row[i]+arr[i][j];
col[i] = col[i] + arr[j][i];
}
printf(" ");
}
for(i=0;i<4;i++)
{
dia1 = dia1 + arr[i][i];
dia2 = dia2 + arr[i][4 - i - 1];
}
printf(" Row sums: ");
for(i =0 ;i<4;i++)
printf("%d ",row[i]);
printf(" column sums: ");
for(i =0 ;i<4;i++)
printf("%d ",col[i]);
printf(" Diagonal sums: %d %d",dia1,dia2);
for(i=0;i<4;i++)
{
if(row[i]==col[i])
flag=1;
else
{
flag=0;
break;
}
}
if(flag==1)
{
if(dia1==row[0]&&dia2==row[0])
flag=1;
else
flag =0;
}
if(flag==1)
printf(" It is a Magic square");
else
printf("It is not a Magic square");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.