Question: I need to do a coin toss simulator. This is the code I've done but it gives results more and less than 2000. Even if I increase the number of loop it gives close to the number but not exact. Every time the results change and there is no specific pattern. Whats wrong with this can you help me ?

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

int rand_coin();     

int main (void) {

      int heads = 0;  
      int tails = 0; 
      srand(time(NULL)); 
      heads = rand_coin();
      tails = rand_coin();
      printf("Heads = %d, Tails = %d\n", heads, tails);
      return 0;
} /* end main */

/* implement rand_coin() below: */

int rand_coin() {
    int value; 
    int i; // 
    int tails = 0;
    int heads = 0; 

    for(i=0; i < 2000; i++)        { 
        value = rand() % 2;  
        if (value == 1) {   
            heads++;
        }
        else {
            tails++;
        }
    }
    return heads;   
}

```

Answer: 
```
  tails = rand_coin();

```

is wrong from an algorithmic point of view. You just need to use:

```
 tails = 2000 - heads;

```

---

I would suggest the following improvements:

1. Pass the number of tosses to `rand_coin` so that the number 2000 is not hard coded in multiple places.
2. There is no need to keep track of `tails` in the function.

Here's an updated version of your posted code.

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

int rand_coin(int num_tosses);

int main (void) {

   int heads = 0;
   int tails = 0;
   srand(time(NULL));
   int num_tosses = 2000;
   heads = rand_coin(num_tosses);
   tails = num_tosses - heads;
   printf("Heads = %d, Tails = %d\n", heads, tails);
   return 0;
} /* end main */

/* implement rand_coin() below: */

int rand_coin(int num_tosses) {
   int value;
   int i; //
   int heads = 0;

   for(i=0; i < num_tosses; i++){
      value = rand() % 2;
      if (value == 1) {
         heads++;
      }
   }
   return heads;
}

```
Your `rand_coin()` function flips 2000 coins and returns the number of heads that appear. Your `main` function calls that twice, independently. There's no reason to think that the result will be exactly 2000.

You only need to call the `rand_coin()` function once to get the number of heads, then subtract from 2000 to get the number of tails.

```
heads = rand_coin();
tails = 2000 - heads;
printf("Heads = %d, Tails = %d\n", heads, tails);

```