Kotlin: Convert Celsius to Fahrenheit

1. Introduction

Temperature is a fundamental physical quantity that describes how hot or cold an object is. Often, depending on the region and application, temperatures are measured in either Celsius or Fahrenheit. In this blog post, we'll develop a Kotlin program to convert a temperature from Celsius to Fahrenheit, bridging the gap between these two commonly used scales.

2. Program Overview

Our Kotlin program will:

1. Prompt the user to input a temperature in Celsius.

2. Capture and store the provided temperature.

3. Convert the temperature from Celsius to Fahrenheit.

4. Display the converted temperature to the user.

3. Code Program

import java.util.Scanner

fun main() {
    // Use Scanner for user input
    val reader = Scanner(System.in)

    // Ask the user to input the temperature in Celsius
    print("Enter temperature in Celsius: ")
    val celsius = reader.nextDouble()

    // Convert Celsius to Fahrenheit using the formula
    val fahrenheit = (celsius * 9/5) + 32

    // Display the converted temperature
    println("$celsius°C is equivalent to $fahrenheit°F.")
}

Output:

Enter temperature in Celsius: 25
25.0°C is equivalent to 77.0°F.

4. Step By Step Explanation

1. Scanner Initialization: We kickstart our program by initializing the Scanner class from the java.util package, allowing us to gather user input. Our instance here is named reader.

2. Temperature Collection: The user is prompted, using the print function, to submit a temperature in Celsius. This temperature is subsequently stored in the celsius variable.

3. Conversion Logic: Celsius to Fahrenheit conversion hinges on a simple formula: multiply the temperature in Celsius by 9/5 and then add 32. We've embodied this formula directly within our Kotlin code.

4. Displaying the Converted Temperature: Lastly, the println function announces the temperature in Fahrenheit to the user, concluding our conversion process.

Comments