Program to convert a temperature from Celsius to Fahrenheit using a union
Program to convert a temperature from Celsius to Fahrenheit using a union
Program to convert a temperature from Celsius to Fahrenheit using a union
Enter temperature in Celsius: -40
Temperature in Fahrenheit = -40.00
#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;
}
Enter temperature in Celsius: -40
Temperature in Fahrenheit = -40.00
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.
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.