haiz haiz
haiz haiz

Reputation: 3

how to create endless random numbers

I tried to generate infinite random number of range 0-9 using while loop, however my code only manage to generate 1 random number before exiting, why is it and how could I change it? Below is my code.

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

int main(void){
    while(1 < 2) {
        srand(time(NULL));
        printf("%d\n", rand() % 9);
    }
    return 0;
}

Upvotes: 0

Views: 235

Answers (1)

unwind
unwind

Reputation: 399703

This:

while (1 < 2)

is of course always true, so the loop will run forever. I tried it, and it works for me at least.

A more concise way of writing an infinite loop is

for (;;)

or maybe

while (true)

but the for version has fewer magical constants so it can be considered better in some dimension.

Also, don't call srand() all the time, that will reset the RNG for each iteration. Just call it once, if you feel you have to, before the loop.

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

int main(void){
    srand(time(NULL));
    for (;;) {
        printf("%d\n", rand() % 10);
    }
    return 0;
}

Also, note that I changed it to % 10, with % 9 you only get numbers in the range 0 through 8, inclusive.

Upvotes: 1

Related Questions