Computer Programming/Conditions/C

From Wikiversity
Jump to: navigation, search

conditions.c[edit]

// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.

#include "stdio.h"

void if_else();
void switch_case();
void to_celsius();
void to_fahrenheit();

int main(void) 
{
    if_else();
    switch_case();
    
    return 0;
}

void if_else()
{
    char choice;

    printf("Enter F to convert to Fahrenheit or C to convert to Celsius:");
    scanf(" %c", &choice);

    if(choice == 'C' || choice == 'c')
    {
        to_celsius();
    }
    else if(choice == 'F' || choice == 'f')
    {       
        to_fahrenheit();
    }
    else
    {
        printf("You must enter C to convert to Celsius or F to convert to Fahrenheit!\n");
    }
}

void switch_case()
{
    char choice;

    printf("Enter F to convert to Fahrenheit or C to convert to Celsius:");
    scanf(" %c", &choice);

    switch(choice)
    {
        case 'C':
        case 'c':
            to_celsius();
            break;
        case 'F':
        case 'f':
            to_fahrenheit();
            break;
        default:
            printf("You must enter C to convert to Celsius or F to convert to Fahrenheit!\n");
    }
}

void to_celsius()
{
    float f;
    float c;

    printf("Enter Fahrenheit temperature:");
    scanf("%f", &f);
    c = (f - 32) * 5 / 9;
    printf("%f° Fahrenheit is %f° Celsius", f, c);
}

void to_fahrenheit()
{
    float c;
    float f;

    printf("Enter Celsius temperature:");
    scanf("%f", &c);
    f = c * 9 / 5 + 32;
    printf("%f° Celsius is %f° Fahrenheit", c, f);
}

Try It[edit]

Copy

See Also[edit]