[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;
}
Advertisements
This entry was posted in General stuffs. Bookmark the permalink.

One Response to [c]Question and Exercise (Tossing chance)

  1. cyruslab says:

    For bypassing the enter character, can use scanf(%s,&choices); the & sign will tell the program to accept the first character of a string.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s