Search⌘ K
AI Features

Random Function

Explore how to create two overloaded random functions in C++. Understand the Linear Congruential Generator algorithm used for producing pseudo-random numbers, and implement these functions to generate both integer and ranged random values. This lesson provides insights into function overloading and random number generation techniques.

We'll cover the following...

Problem

Write a program that provides two overloaded random( ) ...

C++
// Generation of random numbers using overloaded functions
#include <iostream>
int random ( int ) ;
int random ( int, int ) ;
int main( )
{
int i, n ;
std::cout << "Random numbers between 1 to 100: \n";
for ( i = 0 ; i <= 9 ; i++ )
{
n = random ( 100 ) ;
std::cout << n << "\n" ;
}
std::cout << "Random numbers between 100 to 500: \n";
for ( i = 0 ; i <= 9 ; i++ )
{
n = random ( 100, 500 ) ;
std::cout << n << "\n" ;
}
}
int random ( int max )
{
static int xn = time ( NULL ) % max ;
static int cons = time ( NULL ) % 100 ;
static int mult = time ( NULL ) % 120 ;
int xnplus1, temp ;
xnplus1 = ( mult * xn + cons ) % max ;
temp = xnplus1 ;
xn = xnplus1 ;
return ( temp ) ;
}
int random ( int min, int max )
{
int range ;
range = max - min ;
static int xn = time ( NULL ) % range ;
static int cons = time ( NULL ) % 100 ;
static int mult = time ( NULL ) % 120 ;
int xnplus1, temp ;
xnplus1 = ( mult * xn + cons ) % max ;
temp = min + xnplus1 ;
xn = xnplus1 ;
return ( temp ) ;
}

Explanation

...