Magic Square Help

The goal of my assignment is to make a 'Magic Square' with sixteen user input integers.

the actual prompt is, "Magic squares. An n x n matrix that is filled with the numbers 1, 2, 3, ..., n^2 is a magic square if the sum of the elements in each row, column, and two diagonals present are the same value. 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?"

I know I have a long way to go, but right now this is what I have and I can't figure out why it won't properly print my test input array.
EDIT: Thanks to user tpb, the print now comes out properly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>

using namespace std;

int const MAX = 4;
int magic[MAX][MAX]{};

int main()
{
	
	cout << "Please enter 16 integers that you would like to test for the magic square: ";
	string input;
	getline(cin, input);
	stringstream convert(input);
	int num{};
	for(int x{0}; x < MAX; x++)
	{
		for(int y{0}; y < MAX; y++)
		{
			convert >> num;
			magic[x][y] = num;
		}
	}
	for(int x{0}; x < MAX; x++)
	{
		for(int y{0}; y < MAX; y++)
		{
			cout << setw(3) << magic[x][y] << " ";
		}
		cout << endl;
	}
}
Last edited on
Get rid of the do/while loop. The nested for loops inside it already iterate the inner block 16 times.
And you might want to write your output loop like this for spacing:
1
2
3
4
5
	for (int x = 0; x < MAX; x++) {
		for (int y = 0; y < MAX; y++)
			cout << setw(3) << magic[x][y] << ' ';
		cout << '\n';
	}

Last edited on
Thank you tpb for the assist.
Topic archived. No new replies allowed.