### All random number are the same in C Hello,

When I run the below code all ten numbers are the same but when I debug and trace the program, all ten numbers are different.

How can I solve this problem?

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647`` ``````#include #include int generateNum() { int range = 999 - 100 + 1; int num = rand() % range + 100; int yekan = num % 10; int dahgan = (num / 10) % 10; while (yekan % 2 != 0 || dahgan % 2 == 0) { srand(time(0)); num = rand() % range + 100; yekan = num % 10; dahgan = (num / 10) % 10; } return num; } void initArray(int *A, int size) { for (int i = 0; i < size; i++) { A[i] = generateNum(); } } void printArray(int *A, int size) { for (int i = size -1; i >= 0; i--) { printf("%d\t", A[i]); } } int main() { int A; int size = 10; initArray(A, size); printArray(A, size); }`````` srand() should be at the beginning of main(). It is used to seed the random number generator and is only called once. Move line 15 before line 42.

srand(...) seeds the random generator. When you doing it 10 times in the same second you will get 10 values from rand() that are all the same. Thank you. The `time()` http://www.cplusplus.com/reference/ctime/time/
returns a `time_t` object, an arithmetic type that
 generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC

http://www.cplusplus.com/reference/ctime/time_t/

The `srand()` takes `unsigned int`, so time_t must implemently convert to unsigned int.
http://www.cplusplus.com/reference/cstdlib/srand/
If time_t is seconds, then a whole second must pass before the value from time() does change.
 Two different initializations with the same seed will generate the same succession of results in subsequent calls to `rand()`.

Overall, the use of `rand()` is not recommended anymore. C++ Standard Library
has more convenient (albeit more "verbal") solutions.
For example, see: http://www.cplusplus.com/reference/random/uniform_int_distribution/
Topic archived. No new replies allowed.