gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
Program a random C program.
- User
Program a random C program.
- Assistant
Here is a simple C program that generates 5 random numbers between 1 and 10:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int i, random; // Set the seed for the random number generator srand(time(0)); // Generate 5 random numbers between 1 and 10 for (i = 0; i < 5; i++) { random = (rand() % 10) + 1; printf("%d\n", random); } return 0; }Explanation of the code:
- We include the standard libraries
stdio.h,stdlib.h, andtime.h. - In
main(), we declare two integersiandrandom. - We use
srand(time(0))to set the seed for the random number generator based on the current time, so that the random numbers generated will be different each time the program is run. - We use a for loop to generate and print 5 random numbers.
rand()generates a random integer between 0 andRAND_MAX, which is a large constant defined instdlib.h.- We use to get a random integer between 0 and 9, and then add 1 to get a random integer between 1 and 10.
- We include the standard libraries