Question

I am trying to create a 2d matrix board which side is determined by the user input. I created the two D array but it is not printing the right numbers. For example if the user enters 3, it is suppose to create a 3 * 3 board with the number 8, 7, 6, 5, 4, 3, 2, 1, 0.

However it keeps printing the same numbers in each row eg 876, 876, 876

I know it is doing what I have written but I cant figure out how to correct it...I am thinking that I need a counter that resets to zero and perhaps the [i][j] = counter's value.

Anyway here is the code that is giving the trouble.

for (i =0; i< row; i++) 
{  
    for (j =0; j < col; j++)
    {
        game [i][j] = ((row * row)-1) - j;   
        printf( "%i", game[i][j] ); 
    }

How can I populate the board so it prints from (row * col) - 1 to zero. Thanks a million.

Was it helpful?

Solution

for ((i=0, k=0); i< row; i++) 
{  
    for (j =0; j < col; j++)
    {
        game [i][j] = ((row * col)-1) - (k++);   
        printf( "%i", game[i][j] ); 
    }
}

The basic mistake in the code is that, in each iteration, the value getting subtracted from the game[i][j] gets re-initialized to 0. Since, the value of (row * col) is constant for a given value of both, subtracting (0, 1, 2) each time from the sum results in the reproduction of the same numbers.

As given in the example, row=3, col=3, so 3*3 = 9 (Indexed from 0 to 8).

So, we do :

8 - 0 = 8
8 - 1 = 7
8 - 2 = 6

again j gets re-init to 0, so again we have,

8 - 0 = 8
8 - 1 = 7
8 - 2 = 6

.

The solution is, the value getting subtracted should get uniformly reduced, such that it doesn't get re-init inside the loop.

Result :

8 - 0 = 8
8 - 1 = 7
8 - 2 = 6
8 - 3 = 5
.
.
.
.
8 - 8 = 0.

Hope this clears the problem.

OTHER TIPS

As suggested by "self", using a third variable is the easiest way (and actually the most efficient : only one decrement per iteration)

int count = row * col - 1;

for (size_t i =0; i< row; i++)
{
    for (size_t j =0; j < col; j++)
    {
        game [i][j] =  count--;
        printf( "%i", game[i][j] );
    }
}

Output: 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top