Kotlin Program to Convert Celsius to Fahrenheit
You can convert Celsius to Fahrenheit in Kotlin using the formula
fahrenheit = celsius * 9 / 5 + 32. For example: val fahrenheit = celsius * 9 / 5 + 32.Examples
Input0
Output32.0
Input25
Output77.0
Input-40
Output-40.0
How to Think About It
To convert Celsius to Fahrenheit, multiply the Celsius value by 9, then divide by 5, and finally add 32. This formula changes the temperature scale from Celsius to Fahrenheit.
Algorithm
1
Get the temperature value in Celsius.2
Multiply the Celsius value by 9.3
Divide the result by 5.4
Add 32 to the result.5
Return or print the Fahrenheit value.Code
kotlin
fun main() {
val celsius = 25.0
val fahrenheit = celsius * 9 / 5 + 32
println("$celsius Celsius is equal to $fahrenheit Fahrenheit")
}Output
25.0 Celsius is equal to 77.0 Fahrenheit
Dry Run
Let's trace the example where Celsius is 25.0 through the code.
1
Initialize Celsius
celsius = 25.0
2
Multiply by 9
25.0 * 9 = 225.0
3
Divide by 5
225.0 / 5 = 45.0
4
Add 32
45.0 + 32 = 77.0
5
Print result
"25.0 Celsius is equal to 77.0 Fahrenheit"
| Step | Calculation | Result |
|---|---|---|
| Multiply by 9 | 25.0 * 9 | 225.0 |
| Divide by 5 | 225.0 / 5 | 45.0 |
| Add 32 | 45.0 + 32 | 77.0 |
Why This Works
Step 1: Multiply Celsius by 9
Multiplying by 9 scales the Celsius temperature to the Fahrenheit scale proportionally.
Step 2: Divide by 5
Dividing by 5 adjusts the scale difference between Celsius and Fahrenheit degrees.
Step 3: Add 32
Adding 32 shifts the zero point from Celsius to Fahrenheit, aligning freezing points.
Alternative Approaches
Using a function
kotlin
fun celsiusToFahrenheit(celsius: Double): Double {
return celsius * 9 / 5 + 32
}
fun main() {
val tempC = 0.0
println("$tempC Celsius is ${celsiusToFahrenheit(tempC)} Fahrenheit")
}This approach improves code reuse by wrapping the conversion in a function.
Reading input from user
kotlin
fun main() {
print("Enter temperature in Celsius: ")
val celsius = readLine()!!.toDouble()
val fahrenheit = celsius * 9 / 5 + 32
println("$celsius Celsius is equal to $fahrenheit Fahrenheit")
}This approach allows dynamic input from the user instead of hardcoded values.
Complexity: O(1) time, O(1) space
Time Complexity
The calculation uses a fixed number of arithmetic operations, so it runs in constant time.
Space Complexity
Only a few variables are used, so the space needed is constant.
Which Approach is Fastest?
All approaches run in constant time; using a function adds clarity but no significant overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple quick conversion |
| Function | O(1) | O(1) | Reusable code |
| User input | O(1) | O(1) | Interactive programs |
Always use Double type for temperature to handle decimal values accurately.
Forgetting to add 32 after scaling causes incorrect Fahrenheit values.