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 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;
}

                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.