i'm supposed to write a program that simulates cointoss. for each toss the program should print heads or tails and it would toss 100 times and counts the number off times each side of the coin appears. it should also call a seperate function 'flip' that takes no argument and returns 0 for tails and 1 for heads. pease help meeee its due today. this is what i have so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#include <stdafx.h>
#include <iostream>
#include <cstdlib>

using std::cout;
using std::rand;

int flip();

int main(void)
{
    
	int heads = 1;
	int tails = 0;
	int coinToss = 100;
	int face;
	
    for (int toss = 0; toss < coinToss; toss++)
    {
	    flip();
        if (toss == 1)
		
			heads++;
		
		else
		
			tails++;
		
     }
	printf("%s%5s\n", "face", " heads or tails");
	printf(" heads%5d\n",   heads);
	printf(" tails%5d\n",   tails);
	
	
    int flip()
    {
      return rand() % 2;
    
	}
}

i keep getting errors when i execute it and i don't get what i want. also it doesn't call the flip function that gives me 0 for tail and 1 for heads. i need to know if the code is correct.

You have forgotten to use the return value of flip(). If you did this if (flip()==1) . I think you would be a lot better than looking at your loop count varible.

If really helps lots to run you code on paper, with a list of variables when the code is small and you are beginning. They you would see why you only get one head.

It also helps to printout the results every turn.

Comments
Good suggestion on the code runout on paper :)

First seed your rand function.

srand(time(0));

The this code :

for (int toss = 0; toss < coinToss; toss++)
    {
	    flip();
        if (toss == 1)
 
			heads++;
 
		else
 
			tails++;
 
     }

is wrong.

You need to assign the value return to a variable and then use it to compare.

for(int i = 0; i < 100; i++)
{
    int side = flip();
   if(side == 0) tails++;
   else heads++;
}

also you are starting the variable heads at one which will throw off you answer. you should initialize both heads and tails as 0.

This article has been dead for over six months. Start a new discussion instead.