Scala program to convert Celsius to Fahrenheit

1. Introduction

Temperature conversion is a common requirement in many applications, especially those related to weather or physics. In this post, we will explore a Scala program that converts temperatures from Celsius to Fahrenheit.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define the Celsius temperature.

4. Implement a function to perform the conversion.

5. Invoke the function and display the result.

6. Execute the program.

3. Code Program

object TemperatureConverterApp {
  def main(args: Array[String]): Unit = {
    // Define temperature in Celsius
    val celsius = 25.0

    println(s"Converting $celsius°C to Fahrenheit")

    // Convert Celsius to Fahrenheit
    val fahrenheit = celsiusToFahrenheit(celsius)
    println(s"\nResult: $fahrenheit°F")
  }

  // Function to convert Celsius to Fahrenheit
  def celsiusToFahrenheit(celsius: Double): Double = {
    (celsius * 9/5) + 32  // Conversion formula
  }
}

Output:

Converting 25.0°C to Fahrenheit
Result: 77.0°F

Explanation:

1. The program begins with an object named TemperatureConverterApp. Inside this object, the main method acts as our program's entry point.

2. We declare a celsius value which denotes the temperature in Celsius we wish to convert.

3. A message is printed to indicate the conversion operation.

4. The celsiusToFahrenheit function is defined to perform the actual conversion. It utilizes the formula (celsius * 9/5) + 32 to make the conversion.

5. Inside the main function, we call the celsiusToFahrenheit method, retrieve the converted value, and display the Fahrenheit temperature.

6. The output showcases the Celsius value being converted and the resulting Fahrenheit temperature.


Comments