I can't get this code to work for magic squares 4x4 or 5x5, please help
Code:
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
int RandomInt(int n);
void FillSquare (int sq[5][5], int n);
int IsMagic(int sq[5][5], int n);
void PrintSquare(int sq[5][5], int n);
int
main(){
int n;
srand(time(NULL));
/* Ask for the size of the magic square */
printf("Enter the size of magic square, between 3 and 5: ");
scanf("%d", &n);
/* if the number entered isn't between 3 and 5 the program will exit. */
if(n < 3 || n >5)
{printf("number not between 3 and 5, please try again.");
return 0;
}
else
{
int sq[5][5];
int IsMagicTrue=0;
while (!IsMagicTrue)
{
FillSquare(sq, n);
IsMagicTrue=IsMagic(sq, n);
}
PrintSquare(sq,n);
return 0;
}}
/* Creating random integers from 1 to n */
int RandomInt(int n)
{
int r;
r=1+rand()%n;
return r;
}
/* Placing the integers in random spots of the Magic Square that are unoccupied */
void FillSquare (int sq[5][5], int n) {
int x;
int y;
int currentnum;
for(x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{sq[x][y]=0;
}}
currentnum = (n*n);
x = RandomInt(n)-1;
y = RandomInt(n)-1;
while(currentnum > 0)
/* This loop continues until magic square is complete */
{if(sq[x][y] == 0)
{sq[x][y] = currentnum;
currentnum--;
}
x = RandomInt(n)-1;
y = RandomInt(n)-1;
}}
int IsMagic(int sq[5][5], int n)
{
/* Checking each row to see if it is equal to (((n^3)+n)/2) */
int total=0;
int x;
int y;
int total2=0;
for(x = 0; x < n; x++)
{for(y = 0; y < n; y++)
{
total += sq[x][y];
}
if(total != (((n*n*n)+n)/2))
{return 0;}
total=0;
}
/* Checking each column to see if it is equal to (((n^3)+n)/2) */
total=0;
for(y = 0; y < n; y++)
{for(x = 0; x < n; x++)
{
total += sq[x][y];
}
if(total != (((n*n*n)+n)/2))
{return 0;}
total=0;
}
/* Checking each diagonal to see if it is equal to (((n^3)+n)/2) */
total =0;
for(x = 0; x < n; x++)
{
total += sq[x][x];
total2 += sq[n-1-x][x];
}
if(total != (((n*n*n)+n)/2))
{return 0;}
/* Finished all the checks */
return 1;
}
/* This will print the magic square */
void PrintSquare(int sq[5][5], int n)
{
int x;
int y;
for(x = 0; x < n; x++)
{
for(y = 0; y < n; y++)
{
printf(" %d ", sq[x][y]);
}
printf("\n");
}
}