Problem 1:
Magic Squares:
An n x n array, that is filled with integers 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 and each value in the array is unique.
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Write a program that reads in n2 integer values from the user and tests whether they form a magic square when put into an n x n array. You need to test two features:
• does each of the numbers 1 to n2 occur in the user input?
• when the numbers are put into a square, are the sums of the rows, columns and diagonals equal to each other?
Input: n and n2 integer numbers: if the user enters 3, the array has 3 rows and 3 columns and the integers in the array range from 1 to 9. As data validation, be sure the input is in the correct range and that each value is entered only once. (All elements in the array must be unique).
Output: a printout of the n x n array with each row of data on a separate line and a message of whether it is a magic square or not.
That is the problem of my assignment. What I have so far is:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int n;
cout<< "Please enter an odd integer: ";
cin>>n;
int MagicSquare[n][n];
int newRow,
newCol;
// Set the indices for the middle of the bottom i
int i =0 ;
int j= n / 2;
// Fill each element of the array using the magic array
for ( int value = 1; value <= n*n; value++ )
{
MagicSquare[i][j] = value;
// Find the next cell, wrapping around if necessary.
newRow = (i + 1) % n;
newCol = (j + 1) % n;
// If the cell is empty, remember those indices for the
// next assignment.
if ( MagicSquare[newRow][newCol] == 0 )
{
i = newRow;
j = newCol;
}
elsen2 integer values
{
// The cell was full. Use the cell above the previous one.
i = (i - 1 + n) % n;
}
}
for(int x=0; x<n; x++)
{
for(int y=0; y<n; y++)
cout << MagicSquare[x][y]<<" ";
cout << endl;
}
}
The outcome of this is not like the numbers that the assignment have. Getting really frustrated! Please help if you know!!
Thank you!!!