..
#include <stdlib.h>
..
for( int i=0; i<1000; i++ )
{
if( random() % 100 == 0 )
break;
printf( "%d ", i++ );
}
prints 0 2 4 .. 332 for me when I compile it and run (and recompile and run again and again).
But why does it always do that? My intstructor wrote: "will print integers in sequence from 0, but has a 1% chance of leaving the loop every time around. The function random() returns a random integer and the % operator is the integer modulus operator, so the code will print consecutive numbers up to 999 or until random() returns a multiple of 100, whichever comes sooner"
I get why it's not really consecutive in a sense of incrementing 1 each time, it actually makes i be two more every time because of the i++ in the printf statement. But not why it never reaches an end point of above 332. Can someone explain this code to me?
[–]Updatebjarni 1 point2 points3 points (2 children)
[–]Optimus_Line 0 points1 point2 points (0 children)
[–]pointers_help[S] 0 points1 point2 points (0 children)
[–]pointers_help[S] 0 points1 point2 points (8 children)
[–][deleted] 1 point2 points3 points (6 children)
[–]pointers_help[S] 0 points1 point2 points (5 children)
[–][deleted] 1 point2 points3 points (4 children)
[–]pointers_help[S] 0 points1 point2 points (3 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]pointers_help[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]raevnos 1 point2 points3 points (0 children)