Generate random number

You're viewing an older version of this page (#4194). View the current version.

View versions (1)

INTERFACE

#include <stdlib.h>
int rand ( void );

DESCRIPTION

Rand function returns a pseudorandom number. The algorithm used in rand function uses a seed to generate the series, which should be initialized to some distinctive value using srand.

Generate random number

#include <cstdlib> 
#include <ctime> 
#include <iostream>
 
using namespace std;
 
int main() 
{ 
    srand((unsigned)time(0)); 
    int random_integer; 
    for(int index=0; index<20; index++){ 
        random_integer = (rand()%10)+1; 
        cout << random_integer << endl; 
    } 
}

Output: This example of program will output 20 random numbers from 1 to 10.

RETURN VALUES

The rand function returns a pseudo-random integral number between 0 and RAND_MAX (where RAND_MAX is a constant defined in <cstdlib>).

There is no error return.