i had a homework assignment from C how to program 5th edition by dietel (#5.31).
it says:
Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the coin 100 times, and count the number of times each side of the coin appears. Print the results. The program should call a separate function flip that takes no arguments and returns 0 for tails and 1 for heads. [Note: If the program realistically simulates the coin tossing, then each side of the coin should appear approximately half the time for a total of approximately 50 heads and 50 tails.]
Code:
#include <stdio.h>
int flip( );
int main( void )
{
int side;
int toss;
int heads = 0;
int tails = 0;
for ( toss = 1; toss <= 100; toss++ ){
printf( "%d\n", flip( ));
if (flip( ) == 0)
heads++;
else
tails++;
}
printf( "heads was flipped %d times\n", heads );
printf( "tails was flipped %d times\n", tails );
return 0;
}
int flip( )
{
int i = rand() % 2;
if (i == 0)
return 0;
else
return 1;
}
output:
1
0
1
0
0
1
1
1
1
1
1
0
0
1
0
1
1
1
1
1
1
0
1
1
1
1
0
1
1
1
0
0
0
0
0
0
0
0
0
1
1
0
0
0
1
0
0
1
0
1
1
1
0
1
1
1
0
0
1
1
0
1
1
1
1
0
1
0
1
1
1
1
1
1
1
0
0
1
0
0
0
0
0
1
0
1
0
0
0
0
1
1
0
0
1
0
0
1
0
1
heads was flipped 55 times
tails was flipped 45 times
when i run my program it produces the output every time. how can i make it (more random) produce a different output every time it's ran?