Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What is my problem in this code?! how can I fix the calculations so the sum for

ID: 3624316 • Letter: W

Question



What is my problem in this code?!
how can I fix the calculations so the sum for all rows,columns and main diagonals are =34
I got the sums of the rows to be 34!! and I need the diagonals and the columns to give the same result!!

here is the code :


#include <iostream>
using namespace std;

const int MAX= 4;

int main()
{
int n, X, Y, i, j, square[MAX][MAX],s;

for(i =0; i < MAX; i++)

for(j =0; j < MAX; j++)

square[i][j]=0;

X = MAX-1;
Y = MAX/2;

for(n=1;n<=(MAX*MAX);++n)
{
square[X][Y] = n;

if (square[(X+MAX-1)% MAX][(Y+MAX+1)%MAX])

X = (X+MAX+1)% MAX ;

else

X = (X+MAX-1)%MAX , Y = (Y+MAX+1)%MAX ;

}
cout<<"This is the magic square: ";

for(i=0;i<MAX; i++)
{

for(j=0;j<MAX;j++)
{

cout<<" "<<square[j][i];
}
cout<<endl;

s= (1/2.0)*MAX*(1+MAX*MAX);
cout<<endl;


}
cout<<"The Sum of all Rows, Columnas and Diagonal arr added up to the same total = "<<s<<endl;
cout<<endl;

return 0;
}

Explanation / Answer

square[i][MAX] = square[i][MAX]+square[i][j];

}

for(j=0;j<MAX;j++)
{
square[MAX][j] = 0;
for(i =0; i < MAX; i++)

square[MAX][j] += square[i][j]
}

for(i =0; i < MAX; i++)
{
for(j=0;j<MAX;j++)
cout<<square[i][j]<<" ";
}
i = MAX;

for(j=0;j<MAX;j++)
cout<<square[i][j] <<" ";
if(MAX == 4)
{
for(i =0; i < MAX; i++)
for(j=0;j<MAX;j++)
if(i ==j)
s += square[i][j];
else
if(j == MAX-(i+1))
s += square[i][j];;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote