0

I am trying to generate random numbers from 0 to 3 with the rand() function, and it works decently, but I have noticed something odd.

The function keeps producing the same pattern of numbers every time I run and rerun the project.

This is the code I am using broken down as simple as possible..

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

int main()
{
int randomNumber;

for (int i = 0; i < 15; i++)
{
    randomNumber = rand() % 4;
    printf("%d ", randomNumber);
}

getchar();
return 0;
}

And this prints 15 random numbers from 0 to 3, and for me this is what I get

1 3 2 0 1 0 2 2 2 0 1 1 1 3 1

So this is fine. But the issue is, every single time I run the program this exact same thing prints.

Any idea why this is happening?

brent_mb
  • 337
  • 2
  • 13

1 Answers1

1

There is no such thing as a random number in computer science. Therefore to generate different outputs we must use pseudo-random. To do this write srand(time(0)) where you have declared your variables.