[c]Question and Exercise (Tossing chance)

The requirement is to ask user to input head or tail in the program and display the number of heads and tails and the probability in percentage.
output will be like this:

Choose head or tail (valid choices is h or t): h
Choose head or tail (valid choices is h or t): h
Choose head or tail (valid choices is h or t): t
Choose head or tail (valid choices is h or t): t
Choose head or tail (valid choices is h or t): t
Choose head or tail (valid choices is h or t): t
Choose head or tail (valid choices is h or t): t
Choose head or tail (valid choices is h or t): t
Number of heads: 2
Number of tails: 6
Percent heads: 25.00%
Percent tails: 75.00%

Sample code below:

#include <stdio.h>

int main()
{
    int i,hi=0,ti=0;
    char choices;
    float headChance,tailChance;
    for(i=1;i<=8;i++)
    {
        printf("Choose head or tail (valid choices is h or t): ");
        scanf("%c%*c",&choices);
        switch(choices)
        {
            case 'h':
            case 'H':
            hi++;
            break;
            case 't':
            case 'T':
            ti++;
            break;
            default:
            printf("You have entered an invalid choice.\n");
      
        }
    }
    headChance = (float)(hi)/8 * 100;
    tailChance = (float)(ti)/8 * 100;
    printf("Number of heads: %d\n", hi);
    printf("Number of tails: %d\n", ti);
    printf("Percent heads: %.2f%%\n", headChance);
    printf("Percent tails: %.2f%%\n", tailChance);
    return 0;
}
Advertisement

One thought on “[c]Question and Exercise (Tossing chance)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s