14,699,754 members
See more:
I am wondering why the following code fail. I thought it will generate a new number every time the random() function is called, albeit recursively. But it seems that the number remains stationary for a pretty long time before changing. Why is that the case? And how can I change it so that every time it is called, a new number will be generated?

Thanks a lot!

What I have tried:

```#include <time.h>
#include <stdio.h>

int i=0;
int random();

int main(){
random();
return 0;
}

int random(){
int a;
i+=1;
srand(time(NULL));
a=rand()%20;
printf("This is the %d th iteration\n",i);
printf("random number generated is: %d\n",a);
if(a<8)
random();
}```
Posted
Updated 20-Feb-17 13:03pm

You need to learn the basics of random in programming languages. The random numbers generated, are not random. There is a pattern in them.

Read more by Googling. I will not answer. So that you may learn it yourself.

## Solution 1

Google is your friend ... you need to do some research and learn how to use the rand function properly... c rand number[^]

From the google search above: C library function - rand()[^]
```#include <stdio.h>
#include <stdlib.h>

int main()
{
int i, n;
time_t t;

n = 5;

/* Intializes random number generator */
srand((unsigned) time(&t));

/* Print 5 random numbers from 0 to 19 */
for( i = 0 ; i < n ; i++ )
{
printf("%d\n", rand() % 20);
}

return(0);
}```
v3
Member 13013165 20-Feb-17 17:45pm

Hello, thanks for pointing me to google. I will try harder to find a solution first (which I tried previously but probably following the comments from Stack Overflow isn't the best source to understand the issue). As a side note, I must say I am quite discouraged from Stack Overflow. I asked 2 questions and got banned from asking any more questions. I hope I will feel more encouraged asking questions here. Thanks.

## Solution 2

try
```#include <time.h>
#include <stdio.h>

int i=0;
int random();

int main(){
srand(time(NULL));
random();
return 0;
}

int random(){
int a;
i+=1;
a=rand()%20;
printf("This is the %d th iteration\n",i);
printf("random number generated is: %d\n",a);
if(a<8)
random();
}```

The problem is with srand(). the random number generator is not random, it is pseufo-random, it means that if you set the seed 2 times with same value, you will get the same 'random' sequence. And since your seed is a number of seconds, you get every time the same sequence.