C Program to Generate Random Numbers

In this C program, We will learn to generate a sequence of N random numbers between 1 to M. This program takes N(count of random numbers to generates) as input from user and then generates N random numbers between 1 to M(here M = 1000).

It uses rand function of stdlib standard library. It returns a pseudo-random number in the range of 0 to RAND_MAX, where RAND_MAX is a platform dependent value(macro) that is equal to the maximum value returned by rand function.

To generate random numbers between 1 to 1000, we will evaluate rand() % 1000, which always return a value between [0, 999]. To get a value between [1, 1000] we will add 1 to the modulus value, that is rand()%1000 + 1/.

For Example:
(22456 % 1000) + 1 = 457


C program to find n random numbers between 1 to 1000

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

int main() {
    int n, random;
    printf("Enter number of random numbers\n");
    scanf("%d", &n);

    printf("%d random numbers between 0 to 1000\n", n);
    while(n--){
        random = rand()%1000 + 1;
        printf("%d\n", random);
    }

    return 0;
}

Output
Enter number of random numbers
10
10 random numbers between 0 to 1000
243
52
625
841
352
263
582
557
173
625

Related Topics
C program to print all prime numbers between 1 to N using for loop
C program to find gcd of two numbers
C program to generate armstrong numbers
C program to check whether a number is magic number
C program to reverse a number using recursion
C program to count number of digits in an integer
C program to find product of digits of a number using while loop
C program to find ones complement of a binary number
C program to add digits of a number
List of all C programs