rand() in loop

Dear All,

I would like to draw ten random digits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
    int i;
    int rand_a;
    for (i = 0; i<10; i++)
    {
srand(time(NULL));
rand_a = rand()  % 10;
cout<<rand_a<<endl;

    }
    return 0;
}




in efect, I get ten numbers but all of them are the same. What is wrong with my code?

@r0bot

Try taking thesrand(time(NULL)); out of the loop and putting it after int rand_a;.
Take srand(time(NULL)) out of the loop. It only needs to be called once. Put it at the beginning of main.

Also, in case you're not aware, % 10 gives 0 - 9. If you want 1 - 10 (or any range) just add 1 (or however much for the desired range).

Hope this helps!
Last edited on
works well!

thank you guys ;)
Topic archived. No new replies allowed.