More Examples of Random Numbers

Usually, we want to generate random numbers within a specific range, rather than between 0 and 32767. The modulus operator, %, is very handy for this. This example generates 5 numbers between 1 and 10:
#include <iostream.h>  // for cout
#include <stdlib.h>    // for rand()

void main(void)
{
  for (int x = 0; x < 5; x++)
    cout << setw(5) << rand() % 10 + 1;
}

Output:
    7    1    3    1    8
Previous page
Next page

Back to Lesson 12 Index
Back to Outline