codescracker
c

C Program to Generate Random Numbers



« Previous Program Next Program »

In this article, you will learn and get code about generating random numbers. The first program generates 10 random numbers. And the second one generates limited amount of random numbers in a given range. Here limit and range will be entered by user at run-time.

Generate 10 Random Numbers

This program generates 10 random numbers. The function rand() (from stdlib.h) is used to generate random number.

// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
    int i, rnum;
    printf("Generating 10 Random Numbers:\n");
    for(i=0; i<10; i++)
    {
        rnum = rand();
        printf("%d\n", rnum);
    }
    getch();
    return 0;
}

This program was build and run uder Code::Blocks IDE. Here is its sample run:

c program generate random numbers

In above program, the for loop is used to execute the following block of code

rnum = rand();
printf("%d\n", rnum);

10 number of times. At each execution, a random number using rand() gets generated, and initialized to rnum variable. And using printf() function, its value gets printed on output.

Generate Random Numbers in a Range

Here is another program with an extra feature in comparision to above one. It includes a feature that allows user to define the amount (how many random numbers to be generate) and the limit under which, random numbers has to be generated.

// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
    int i, rnum, amount, start, end;
    printf("Enter Interval: ");
    scanf("%d%d", &start, &end);
    printf("\nHow many Random Numbers to Generate ? ");
    scanf("%d", &amount);
    printf("\nGenerating %d Random Numbers between %d and %d:\n", amount, start, end);
    srand(time(0));
    for(i=0; i<amount; i++)
    {
        rnum = rand()%(end+1-start)+start;
        printf("%d\n", rnum);
    }
    getch();
    return 0;
}

The sample run given below generates 10 random numbers between 0 and 10. This value is entered by user at run-time.

generate random numbers in range c

If the function srand() was not used in above program, then at second sample run (with same user input), all the 10 random numbers were same. Therefore, to generate new random numbers on every sample run, use srand() function.

And here is another sample run that will generate 10 random numbers between 1 and 100:

c program random numbers

Same Program in Other Languages


« Previous Program Next Program »