I have an issue understanding the “do – while” statement in C.
Here is the complete code: http://pastebin.com/uPRvRscd
The program generates 6 numbers ranged from 0 to 50.
None of the 6 numbers repeats.
This is the do-while loop:
for(c=0;c<BALLS;c++)
{
/* See if a number has been allready been drawn */
do
{
ball = rand() % RANGE; /* Generate the random ball */
}
while(numbers[ball]); /* How is this compare made ? */
/* Number drawn */
numbers[ball] = 1; /* What is this for ?!? */
printf("%2d ", ball+1); /* add 1 to ball so ball won't be zero */
}
-
How does the logical compare work ?
I know that the DO depends if the WHILE is true or false.
numbers[ball] = 1; What is this supposed to do ? ( if i remove it the result is the same )
Thank you
C has a rule that “anything that is zero” is false, everything else is true. So when you write
if(x)it is the same asif (x != 0)andif(!x)meansif (x == 0).Same wit conditions in
for,whileanddo–while.So your code does:
I assume that
numbersis an array of 50, that is filled with zero [if it’s of static storage duration, then it’s automatically set to zero if nothing else is stated.]When a number has been drawn
numbers[ball] = 1;sets that number to non-zero, so if we draw the same number again, the do-while loop will loop again and pick another number [we hope – if the random number generator is really rubbish, it may turn into an infinite loop]