# Thread: 4x4 grid in C

1. ## 4x4 grid in C

Dear all,
i am just starting to learn about C.. anyone can help with my question will be appreciated.

How to build a 4x4 grid with the following condition :
sum of each row equal 34;
sum of each column equal 34;
no number can be repeated;

i dont like to hard coded it... i prefer to use loop to have the program work...

Roberto.

2. At least show some effort, nobody's gonna write the whole thing out for you
how would you do it if you were to solve this problem manually?

3. Well there problem has a name and it is called magic squares. You are asked to write a program that will produce a magic square array of 4. A magic square of n has in each row - col - diag sum(n) = (n^3 + n) / 2 , in our case n = 4 which means sum(4) = 34.
The answer after a quick search is that for numbers like 4, 6, 8 e.g, for even numbers there is no specific algorithm that produces a magic square. There is a simple technique though that can solve your problem. Just start diging somewhere and you will find it, give us a try of your code and we will help you.

4. ## 4 X 4 grid

Thank you for the explanation..
I am able to generate the number using rand(), my question is that what to do so that it can check the random number so that the same number is not appear twice?

Thanks

Originally Posted by Bokarinho
Well there problem has a name and it is called magic squares. You are asked to write a program that will produce a magic square array of 4. A magic square of n has in each row - col - diag sum(n) = (n^3 + n) / 2 , in our case n = 4 which means sum(4) = 34.
The answer after a quick search is that for numbers like 4, 6, 8 e.g, for even numbers there is no specific algorithm that produces a magic square. There is a simple technique though that can solve your problem. Just start diging somewhere and you will find it, give us a try of your code and we will help you.

5. Code:
```do
{
int go=0;
num = rand();
if (num == prev_num)
go = 1;

} while (go);```

6. ## re : 4 x 4 grid in C

thanks for the explanation... my question is where to put the code?

Here is my code :
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;
}```