About Random numbers!

How to generate Random numbers?

We can generate Random numbers by using rand() or random() function. This is defined in "stdlib.h".
Example below illustrates to generate Random number.

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

int main()
{
    int i;
    int num;
    int range;
    
    num = random();  // or else use rand()
    printf("\nnum : %d", num);

    num = random(); // or else use rand()
    printf("\nnum : %d", num);
    
    return 0;
}

But everytime you run this program, it will give same series. Starting number is decided by the seed, which is always initialized by 0 for rand(). If we want a different series, we need to initiate seed value using srand(int). That means, for a particular seed value, we always get one series.

srand(int);

Good way of initiating seed value is by using time, so that everytime we get different value for seed. See the example below:

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

int main()
{
    int i;
    int num;
    int range;
    time_t seconds;
    
    time(&seconds);
    srand((unsigned int) seconds);

    num = rand();
    printf("\nnum : %d", num);

    num = rand();
    printf("\nnum : %d", num);
    
    return 0;
}

By default, it will generate random numbers between 1 & the Max value of rand(). The max value is system dependent as by naive its of type "int".
The max value is defined by the macro RAND_MAX, which is also defined in "stdlib.h".

If we want to generate random numbers till a maximum number then say:
rand()%range;

The following program illustrates how to generate random numbers till a given max number. Here 10 is considered as max number.
#include < stdio.h >
#include < stdlib.h >
#include < time.h >

int main()
{
    int i;
    int num;
    int range;
    time_t seconds;
    
    time(&seconds);
    srand((unsigned int) seconds);

    num = rand()%10;
    printf("\nnum : %d", num);

    num = rand()%10;
    printf("\nnum : %d", num);
    
    return 0;
}

Note:
If we want to continuosly display the random numbers by keeping rand() in a loop, then we may not get the exactly random numbers. The output will be correct only if we are using the range from 1 - RAND_MAX. In all other cases, random numbers is not gauranteed.
Find the below code:
 
#include < stdio.h >
#include < stdlib.h >
#include < time.h >

int main()
{
    int i;
    int num;
    int range;
    time_t seconds;
    
    printf("\nEnter the Max no. in random numbers : ");
    scanf("%d", &range);
    
    time(&seconds);
    srand((unsigned int) seconds);
    printf("\nSeconds : %d", seconds);
    for(i=1; i<=range-1; ++i)
    {
        num = random()%range+1;
        printf("\nnum : %d", num);
    }
    
    return 0;
}

Bigger the range value, we may get the most accurate output.

Comments

Popular posts from this blog

GCC Extenstion

What is Code Bloat?

Method Chaining.