Convert Celsius to Fahrenheit and Back Using Switch Statement in C

This program converts a given temperature from Celsius to Fahrenheit or Fahrenheit to Celsius, based on the user’s choice, using a switch statement.

C Program

#include <stdio.h>

int main() {
    int choice;
    float temp, result;

    printf("1. Celsius to Fahrenheit\n2. Fahrenheit to Celsius\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    printf("Enter temperature: ");
    scanf("%f", &temp);

    switch (choice) {
        case 1:
            result = (temp * 9 / 5) + 32;
            printf("%.2f Celsius = %.2f Fahrenheit\n", temp, result);
            break;
        case 2:
            result = (temp - 32) * 5 / 9;
            printf("%.2f Fahrenheit = %.2f Celsius\n", temp, result);
            break;
        default:
            printf("Invalid choice.\n");
    }

    return 0;
}

Explanation

  • The user first picks the conversion direction, then enters the temperature value.
  • Celsius to Fahrenheit uses the formula (C × 9/5) + 32.
  • Fahrenheit to Celsius uses the formula (F − 32) × 5/9.
  • The switch statement selects the correct formula based on choice, and default handles invalid menu selections.

Sample Output

1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your choice: 1
Enter temperature: 100
100.00 Celsius = 212.00 Fahrenheit

Leave a Comment