Random number generator? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Random number generator?

How can I make a c++ program that generates a random number between 1 and 10 and generates a new number each time the program runs. I was able to make it generate a random number, but it was the same every time I ran the program.

26th Jan 2019, 5:01 AM
Daniel Cooper
Daniel Cooper - avatar
3 Answers
+ 2
You need to use the function srand(time(0)) to make so that the algorythn will generate random number based on the system clock, so you will have a different number everytime: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main () { srand(time(0)); for (int x = 1; x <= 10; x++) { cout << 1 + (rand() % 10) << endl; } } The above code will output random number between 1 and 10 To use the time() func you need to implement the header <ctime>!
26th Jan 2019, 5:18 AM
Sekiro
Sekiro - avatar
26th Jan 2019, 5:24 AM
Daniel Cooper
Daniel Cooper - avatar
0
Yes, nice job!
26th Jan 2019, 8:00 AM
Sekiro
Sekiro - avatar