Home / Programs / Program to convert a temperature from Celsius to Fahrenheit using a union
Programming Example

Program to convert a temperature from Celsius to Fahrenheit using a union

👁 277 Views
💻 Practical Program
📘 Step by Step Learning

Program to convert a temperature from Celsius to Fahrenheit using a union

Information & Algorithm

Given Input:

Enter temperature in Celsius: -40

Expected Output:

Temperature in Fahrenheit = -40.00

Program Code

#include <stdio.h>

union Temperature {
    float celsius;
    float fahrenheit;
};

int main() {
    union Temperature temp;
    
    printf("Enter temperature in Celsius: ");
    scanf("%f", &temp.celsius);
    
    temp.fahrenheit = (temp.celsius * 9.0 / 5.0) + 32.0;
    
    printf("Temperature in Fahrenheit = %.2f\n", temp.fahrenheit);
    
    return 0;
}

Output

Enter temperature in Celsius: -40
Temperature in Fahrenheit = -40.00

Explanation

In this program, we define a union "Temperature" that can store either a temperature in Celsius or a temperature in Fahrenheit. We then use the union to convert a temperature from Celsius to Fahrenheit.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.