# Thread: 4 x 4 Magic Square

1. ## 4 x 4 Magic Square

Dear all,
Wondering how to check so that same number will not appear twice in the grid, if number appeared then program generate random number again..

Code:
```#include <stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>

#define SIZE 4
#define TOTALVALUE 34

int random(void);
int checkArray(int array[SIZE][SIZE]);
void generateArray(int array[SIZE][SIZE]);
const int MAX = 17;

int main (void)
{
int array[SIZE][SIZE];
int i;
int j;

for(i=0; i < SIZE; i++)
{
for(j = 0; j < SIZE; j++)
{
array[i][j] = random();

//int number;
//number = rand();
//printf("%i\t",(number % (MAX-1)) +2);
printf("%i\t", array[i][j]);
}printf("\n");
}
fflush(stdin);

return 0;
}

int random(void)
{
/*int i;
int a;

for (i = 0; i < 4; i++)
{
for(a = 0; a < 4; a++)
{*/

int number;

number = rand() % (MAX-1) +2;

return number;
}```

2. There is nothing random about a magic square. I'm pretty sure there is only 1 possible square with 4x4 dimensions that sums to 34.
Code:
```int magic[4][4] =
{
{ 1 , 2 , 3 , 4 , },
{ 5 , 6 , 7 , 8 , },
{ 9 , 10, 11, 12, },
{ 13, 14, 15, 16, },
};```
Adding up the diagonal will give you the sum of the square. Now just swap the numbers around so that the magic square property holds, and you have your square.

3. The following code fills an array of integers with random unique numbers, meaning that the numbers will not duplicate in the array but will still be random.
The way is similar for a 4 * 4 or N * N array, just think of it and tell me if you need any assistance.

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

void FillArrayRandomIntegers(int *ptrArray, const int ptrArraySz, const int lowLim, const int highLim)
{
if(!ptrArray)
{
printf("Array is NULL.\n");
return;
}
else
{
/* Holds the value of rand(). */
int randVal = 0;
/* Index for Array. */
int ptrIndex = 0;
int randIndex = 0;
/* Initiate Random Gen. */
srand(time(NULL));
/* Perform Loop. */
do
{
randVal = rand() % highLim + lowLim;
/* Apply value to the array. */
ptrArray[ptrIndex] = randVal;
/* Check array for duplicate number. */
for(randIndex = 0; randIndex < ptrIndex && ptrArray[ptrIndex] != ptrArray[randIndex]; randIndex++);
if(randIndex == ptrIndex)
ptrIndex++;
}while(ptrIndex < ptrArraySz);
}
}

void Dump1DArray(const int *ptrArray, const int Sz)
{
int i;
for(i = 0; i < Sz; i++)
printf("%d ", *(ptrArray + i));
printf("\n\n");
}

int main(int argc, char *argv[])
{
int ptr[10] = {0};
FillArrayRandomIntegers(ptr, 10, 1, 10);
Dump1DArray(ptr, 10);
system("PAUSE");
return 0;
}```
The code was implemented in DevC++ IDE, miss my TurboC++ which i use at home, keep up...