C - Write program to generate random int numbers between 0 and 20

Requirements

Write program to generate random int numbers between 0 and 20

Hint

Use the modulus assignment operator to limit the range of the random numbers.

The format looks like this:

r%=n; 

r is the number returned from the rand() function.

%= is the modulus assignment operator.

n is the range limit, plus 1.

After the preceding statement, values returned are in the range 0 through n-1.

So if you want to generate values between 1 and 100, you would use this formula:

value = (r % 100) + 1; 

Demo

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

int main()/*  w  w w  .  j ava2 s  . c o  m*/
{
    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);
}

Result

Related Exercise