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;
}

```
Referring to the example you gave in a comment: 

> 
> If you flip a coin 10 times you get 10 results either heads or tails. for example, I was getting 964 heads 951 tails. which is less than 2000. If you flip a coin x times you can get x results.
> 
> 
> 

If you read your code with reference to that example the following happens:

You flip a coin 2000 times and get 964 heads and 1036 tails, for a total of 2000; but you only make the 964 heads visible by returning them from the function.  

Then you flip a coin 2000 times again, and get 951 heads, not tails and 1049 tails, for a total of 2000 results. 

Counting totals you have 1915 heads and 2085 tails, for a total of 4000, which equals 2\*2000. Each of the two calls has generated 2000 results and reported only part of that as heads, correctly.