w3resource

Scala Programming: Get the absolute difference between n and 51

Scala Programming Basic Exercise-3 with Solution

Write a Scala program to get the absolute difference between n and 51. If n is greater than 51 return triple the absolute difference.

Sample Solution:

Scala Code:

object scala_basic {
  def test(x:Int) : Int =
    {
    val abs_Diff = Math.abs(x - 51)
    if (x > 51) 3 * abs_Diff else abs_Diff
    }
     
   def main(args: Array[String]): Unit = {
      println("Result: " + test(60));
      println("Result: " + test(40));
   }
}

Sample Output:

Result: 27
Result: 11

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to compute the sum of the two given integer values. If the two values are the same, then return triples their sum.
Next: Write a Scala program to check two given integers, and return true if one of them is 30 or if their sum is 30.

What is the difficulty level of this exercise?