Solution for Exercise 11-18
ex1118
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r,a,b;
puts("100 Random Numbers");
for(a=0;a<20;a++)
{
for(b=0;b<5;b++)
{
r=rand();
r%=21;
printf("%d\t",r);
}
putchar('\n');
}
return(0);
}
Output
100 Random Numbers
7 7 2 20 13
20 9 8 8 1
6 2 0 20 0
5 16 4 4 10
18 19 15 14 1
3 6 9 14 16
4 17 14 13 8
12 7 1 0 18
13 14 7 0 2
5 11 4 6 16
2 5 7 1 7
17 9 14 6 7
19 7 12 17 8
1 0 0 9 10
7 13 19 13 0
1 14 12 20 5
6 10 0 7 8
17 18 17 3 3
18 8 11 16 12
20 13 12 11 3
Notes
* The zero is possible because r%=21 generates a value of zero when the random number coughed up by the rand() function is divisible by 21.
* You could also combine Lines 13 and 14 to read:
* Or you could set r%21 as the printf() statement's argument instead of just r. In this case, you could remove Line 14 from the code. And you could eliminate int variable r from the code if you set rand()%21 as the second argument in the printf() statement.
* Most of the random number generating routine you use incorporate the modulus operator to curb the values, just as shown above.
Copyright © 1997-2026 by QPBC.
All rights reserved
