- Write a C program to print N random numbers between 1 to M.
- How to print a sequence of random numbers.
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
/* * C program to print 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); /* print n random numbers using rand function */ printf("%d random numbers between 0 to 1000\n", n); while(n--){ random = rand()%1000 + 1; printf("%d\n", random); } getch(); return 0; }
Program Output
Enter number of random numbers 10 10 random numbers between 0 to 1000 243 52 625 841 352 263 582 557 173 625