C++ MAGIC SQUARE write a program that generates a magic square for an array of s
ID: 654900 • Letter: C
Question
C++ MAGIC SQUARE
write a program that generates a magic square for an array of size 3*3.
step1: use a 2d array of 3*3
step2: fill array with unique values 1-9 genrerated at random
use a function to check and see if the random numbers generated have been previously generated in the array,(check for unqiueness)
if the number is unique,store it in your 2d array
step3:display the 2d array
step4:check if thr 2d array is a magic square
(sum of each row=sum of each col.=sum of each diagonal)
step5:keep repeating the loop of steps1-4 until a magic square is found.
EX:
1 2 3
4 5 6
7 8 9
Not magic
2 3 1
4 5 6
7 8 9
not Magic
2 7 6
9 5 1
4 3 8
IS Magic
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <cmath>
int size;
void write(void);
void fillWithZero(int [][1024]);
void magicSquare(int [][1024]);
void drawTable(int [][1024]);
int isWritable(int);
int outOfBounds(int, int);
int main()
{
do
{
std::cin >> size;
} while(size % 2 == 0);
write();
return 0;
}
void write()
{
int grid[size][1024];
magicSquare(grid);
drawTable(grid);
}
void fillWithZero(int _array[][1024])
{
int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
_array[i][j] = 0;
}
}
}
int isWritable(int n)
{
return (n == 0) ? 1 : 0;
}
int outOfBounds(int max, int n)
{
if( n > max )
{
return 1;
}
if ( n < 0 )
{
return -1;
}
return 0;
}
void magicSquare(int grid[][1024])
{
fillWithZero(grid);
int max = size - 1;
int startY = size / 2;
int startX = max;
int col = startY;
int row = startX;
int i;
int lastCol;
int lastRow;
for(i = 1; i <= (size * size); i++)
{
grid[col][row] = i;
lastRow = row;
lastCol = col;
row++;
col++;
if ( outOfBounds(max, row) == 1 )
{
row = 0;
}
if ( outOfBounds(max, col) == 1 )
{
col = 0;
}
if ( ! isWritable(grid[col][row]) )
{
row = lastRow - 1;
col -= 1;
if( outOfBounds(max, row) == -1)
{
row = max;
}
if( outOfBounds(max, col) == -1)
{
col = max;
}
}
}
}
void drawTable(int grid[][1024])
{
int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
std::cout << grid[i][j] << " ";
}
std::cout << std::endl;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.