📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
Generating random numbers in programs can be useful for various reasons such as simulations, games, and testing. In C, we can produce random numbers with the help of the rand() function available in the stdlib.h library. However, by default, this function generates the same sequence of numbers every time the program runs. To overcome this and produce a different sequence on each execution, we use the srand() function with the current time as the seed.
2. Program Overview
1. Include necessary header files.
2. Use srand() to initialize the random number generator with the current time.
3. Use the rand() function to generate random numbers.
4. Display the generated numbers.
3. Code Program
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, n;
// Initialize random number generator
srand(time(0));
printf("How many random numbers do you want to generate?: ");
scanf("%d", &n);
printf("Random Numbers: \n");
for(i = 0; i < n; i++) {
printf("%d\n", rand());
}
return 0;
}
Output:
How many random numbers do you want to generate?: 5 Random Numbers: 12345 67890 23456 78901 23457 (Note: Actual numbers will vary on each execution.)
4. Step By Step Explanation
1. The program begins by including the necessary header files: stdio.h for input/output functions, stdlib.h for the rand() and srand() functions, and time.h for the time() function.
2. The random number generator is initialized using the current time (time(0)) as the seed. This ensures that each time the program runs, we get a different sequence of random numbers.
3. The user is prompted to enter the number of random numbers they wish to generate.
4. A loop runs as many times as the user specifies, and inside this loop, the rand() function is called to produce a random number, which is then printed.
Comments
Post a Comment
Leave Comment