What means rand() % range + lower?

Viewed 75

Im learning C right now and I don't understand what the rand() % range + lower in this line of code means.

printf("I will generate 10 random numbers between %d and %d . . .\n", lower, upper);

int range = upper - lower+1;                        
for(int i = 0; i <= 10; i++) {                      
    int number = rand() % range + lower;            
    printf("%d\t", number);
2 Answers

This is a poor man's linear random generator.

It is indeed random because is is fed from rand() which returns an random integer, and by construction the value is >= lower and <= upper.

But it is still a poor man's tool because the values in the [lower, upper] interval may have different probabilities.

Long story made short, it can be used if you just need some random values but should not be if you need a cryptographic secure random source.

Please read abut % operator. It is modulo division. Modulo division is good tool to uniform mapping biggest range to shortest range (in your case rand() % range). You just need add start of range to shift all values to correct positions. Code rand() % range + lower is standard C idiom to get random numbers from A,B range. You can find more idioms, for example for floating-points numbers with (A,B) range or <A,B> range.

Related