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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<stdio.h>
#include<stdlib.h>

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[10];
	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.