# Generating random numbers

```c
int rand(void);
```

:::{literalinclude} ../code/random_numbers_without_seed.c
:language: c
:::
:::{literalinclude} ../code/random_numbers_without_seed.txt
:language: text
:::
Running the program again:
:::{literalinclude} ../code/random_numbers_without_seed.txt
:language: text
:::

:::{card} 🤔 Question to ponder
Would you call `rand` a random number generator?
:::
<!-- rather a pseudo-random generator-->

:::{wpd} pseudorandom number generator
an algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers – also known as *deterministic random bit generator*. ... is not truly random, because it is completely *determined by an initial value*, ... called *seed*.
:::
:::{wpd} random seed
a number used to initialize a pseudorandom number generator
:::

:::{activity} Generating random numbers in an interval
:label: generating-random-numbers-in-an-interval
1. Write code that generates five random numbers in the range [0, 4] and prints them.
2. Do you think that this way of generating numbers is useful in our problem?
<!-- they are deterministic-->
:::

## Generating a different sequence

```c
void srand(unsigned int seed);  // seed random number generator
```

From [rand manual](https://man.archlinux.org/man/rand.3):

> If no seed value is provided, the rand() function is automatically seeded with a value of 1.

:::{literalinclude} ../code/random_numbers_with_seed.c
:language: c
:::
:::{literalinclude} ../code/random_numbers_with_seed.txt
:language: text
:::

On my system, `srand(0)` and `srand(1)` have the [same effect](https://stackoverflow.com/questions/8049556/what-s-the-difference-between-srand1-and-srand0).

:::{card} 🤔 Question to ponder
Do you think that this way of generating numbers is useful in our problem? Why?
<!-- still deterministic -->
:::

## Generating a different sequence at each run

Example using the time now as a seed.

:::{literalinclude} ../code/random_numbers_with_seed_and_time.c
:language: c
:::
:::{literalinclude} ../code/random_numbers_with_seed_and_time.txt
:language: text
:::
Running the program again:
:::{program-output} make --silent -C code random_numbers_with_seed_and_time && ./code/random_numbers_with_seed_and_time
:shell:
:::

:::{activity} Generating random numbers in an interval for a game
Modify your code from {numref}`generating-random-numbers-in-an-interval` so that it is useful for our problem
:::