C Program to Convert Celsius to Fahrenheit
fahrenheit = (celsius * 9 / 5) + 32; and print the result with printf.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { float celsius, fahrenheit; printf("Enter temperature in Celsius: "); scanf("%f", &celsius); fahrenheit = (celsius * 9 / 5) + 32; printf("Temperature in Fahrenheit: %.2f\n", fahrenheit); return 0; }
Dry Run
Let's trace the input 25 through the code
Input Celsius
User enters 25, so celsius = 25
Calculate Fahrenheit
fahrenheit = (25 * 9 / 5) + 32 = 45 + 32 = 77
Print Result
Prints 'Temperature in Fahrenheit: 77.00'
| Step | Celsius | Fahrenheit |
|---|---|---|
| Input | 25 | - |
| Calculation | 25 | 77 |
| Output | 25 | 77 |
Why This Works
Step 1: Read Celsius Input
The program uses scanf to get the Celsius temperature from the user.
Step 2: Apply Conversion Formula
It calculates Fahrenheit by multiplying Celsius by 9, dividing by 5, then adding 32 using fahrenheit = (celsius * 9 / 5) + 32;.
Step 3: Display Fahrenheit
Finally, it prints the Fahrenheit temperature with two decimal places using printf.
Alternative Approaches
#include <stdio.h> int main() { int celsius, fahrenheit; printf("Enter temperature in Celsius: "); scanf("%d", &celsius); fahrenheit = (celsius * 9 / 5) + 32; printf("Temperature in Fahrenheit: %d\n", fahrenheit); return 0; }
#include <stdio.h> float toFahrenheit(float celsius) { return (celsius * 9 / 5) + 32; } int main() { float celsius; printf("Enter temperature in Celsius: "); scanf("%f", &celsius); printf("Temperature in Fahrenheit: %.2f\n", toFahrenheit(celsius)); return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic operations and input/output calls, so it runs in constant time.
Space Complexity
It uses a few variables for input and output, so space usage is constant.
Which Approach is Fastest?
All approaches run in constant time; using integers is slightly faster but loses precision, while using functions improves readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Float calculation inline | O(1) | O(1) | Precision and simplicity |
| Integer calculation | O(1) | O(1) | Simple cases without decimals |
| Function-based conversion | O(1) | O(1) | Code organization and reuse |