Home > Software design >  While loop in C which genrates random numbers running for infinity
While loop in C which genrates random numbers running for infinity

Time:11-03

I want to make a program, which generates 2 random coordinates and then it tests if the place in the 2D array I made before is empty (the value in the array is 0). If true, it places value 2 to that coordinates, else it should keep looking for such place. The issue is that it is running for infinity in some cases.

Here is the array I made:

int array[4][4] =
{
    {0,0,0,0},
    {0,0,0,0},
    {0,0,0,0},
    {0,0,0,0}
};

Here is the rest of the code:

srand(time(NULL));
int ranadom_num[2] = { rand() % 4, rand() % 4 };
while (array[ranadom_num[0]][ranadom_num[1]] != 0)
{
    int ranadom_num[2] = { rand() % 4, rand() % 4 };
}
array[ranadom_num[0]][ranadom_num[1]] = 2;

Any help? :)

CodePudding user response:

There are two variables in given piece of code,

int ranadom_num[2] = { rand() % 4, rand() % 4 }; //here 1

while (array[ranadom_num[0]][ranadom_num[1]] != 0)
{
    int ranadom_num[2] = { rand() % 4, rand() % 4 }; //here 2
}

so, random_num picked at 1 is not changed inside the loop and random_num at 2 is of no use as it is unused in the given scope (i.e inside loop).

Find the updated code here,

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int
main ()
{
  int array[4][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12},
    {0, 0, 0, 0}
  };

  srand (time (NULL));
  int ranadom_num[2] = { rand () % 4, rand () % 4 };
  while (array[ranadom_num[0]][ranadom_num[1]] != 0)
    {
      printf ("%d ", array[ranadom_num[0]][ranadom_num[1]]);
      ranadom_num[0] = rand () % 4;
      ranadom_num[1] = rand () % 4;
    }
  array[ranadom_num[0]][ranadom_num[1]] = 2;

  return 0;
}

You also need to take care of values inside array. At lease one element must be zero to terminate the loop else it will be infinite loop.

CodePudding user response:

You're redeclaring ranadom_num in the loop and you're not setting the value in the array until after the loop completes, which is why you're getting the infinite loop.

srand(time(NULL));
int ranadom_num[2] = { rand() % 4, rand() % 4 };
while (array[ranadom_num[0]][ranadom_num[1]] != 0)
{
    //now there's a chance that the array will have a 2 in it
    array[ranadom_num[0]][ranadom_num[1]] = 2; 
    ranadom_num[0] = rand() % 4;
    ranadom_num[1] = rand() % 4;
}
  • Related