(rand() % 100 + 1)

"(rand() % 100 + 1)" - why does it give random number < 100? I started to learn c++ couple of weeks ago in my spare time. Most of codes and tutorials I do undestand, however the one mentioned above I do not get. I will appreciate any good explanation of this. Thank you :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// random.cpp
// Outputs 20 random numbers from 1 to 100.
#include <stdlib.h>
 // Prototypes of srand() and rand()
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
unsigned int
 i, seed;
cout << "\nPlease type an integer between "
"0 and 65535: ";
cin >> seed;
 // Reads an integer.
srand( seed);
 // Seeds the random
// number generator.
cout << "\n\n
 "
"******
 RANDOM NUMBERS
 ******\n\n";
for( i = 1 ; i <= 20 ; ++i)
cout << setw(20) << i << ". random number = "
<< setw(3) << (rand() % 100 + 1) << endl;
return 0;
}
rand() gives a random number between 0 and RAND_MAX, inclusive (RAND_MAX might be something like 65536, depending on your compiler).

rand() % 100 then takes the remainder of this number when you divide by 100 (otherwise known as "modulus"). In other words, it produces a number between [0, 99], inclusive.
For example, 124 % 100 == 24, 99 % 100 == 99, 100 % 100 == 0.

rand() % 100 + 1 takes the previous result, and adds 1 to it, giving you an range of [1, 100], inclusive.

Does that help understand what's happening?
Perfect explanation! Thank you
while you are learning, look at replacing rand (a bit of a relic from years back) with random:

http://www.cplusplus.com/reference/random/?kw=random
Topic archived. No new replies allowed.