In the realm of programming, mastering the art of writing efficient and modular code is crucial. The conversion of temperature units, such as Celsius to Fahrenheit, is a common task that can be elegantly accomplished using C programming with the implementation of functions.
Understanding Celsius to Fahrenheit Conversion
The conversion formula from Celsius to Fahrenheit is
F = 5/9×C+32
Where F represents the temperature in Fahrenheit, and C represents the temperature in Celsius
C Program to Convert Celsius to Fahrenheit Using Functions
Let’s write a C program that incorporates a function to convert Celsius to Fahrenheit –
#include <stdio.h>
float celsiusToFahrenheit(float celsius) {
return (celsius * 9 / 5) + 32;
}
void main() {
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = celsiusToFahrenheit(celsius);
printf("%.2f Celsius is equal to %.2f Fahrenheit\n", celsius, fahrenheit);
}
Output
How the Above C Program Works
- The
celsiusToFahrenheit()
function takes a temperature value in Celsius as input and returns the equivalent temperature in Fahrenheit using the conversion formula. - In the
main()
function, the user inputs the temperature in Celsius. - The program then calls the
celsiusToFahrenheit()
function, passing the Celsius temperature entered by the user as an argument. - Finally, the program displays the converted temperature in Fahrenheit to the user.
The creation of a C program to convert Celsius to Fahrenheit using functions exemplifies the significance of modular programming. By encapsulating the conversion logic within a function, programmers can write cleaner, more maintainable code, facilitating easier debugging and modification.