Scala Programming: Compute the sum of the two given integer values
Scala Programming Basic Exercise-2 with Solution
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.
Sample Solution:
Scala Code:
// Define an object named scala_basic
object scala_basic {
// Define a function named test with parameters x and y, returning an Int
def test(x: Int, y: Int): Int =
{
// Check if x is equal to y
if (x == y)
// If true, calculate (x + y) * 3 and return the result
(x + y) * 3
else
// If false, calculate x + y and return the result
x + y
}
// Define the main method, which is the entry point of the program
def main(args: Array[String]): Unit = {
// Print the result of calling test with arguments 1 and 2
println("Result: " + test(1, 2))
// Print the result of calling test with arguments 2 and 2
println("Result: " + test(2, 2))
}
}
Sample Output:
Result: 3 Result: 12
Explanation:
Here is the break down of the said Scala code:
- object scala_basic {: This declares an object named scala_basic.
- def test(x: Int, y: Int): Int =: This line defines a function named 'test' that takes two parameters, x and y, both of type Int, and returns an Int. The function body is enclosed in curly braces.
- if (x == y) (x + y) 3 else x + y: This is a conditional expression inside the "test()" function. It checks whether x is equal to y. If true, it calculates and returns the result of (x + y) 3; if false, it calculates and returns the result of x + y.
- def main(args: Array[String]): Unit = {: This line defines the main method, which is the entry point of the program. It takes an array of strings (args) as its parameter and returns Unit (similar to void in other languages).
- println("Result: " + test(1, 2)): This line calls the "test()" function with arguments 1 and 2, concatenates the result with the string "Result: ", and prints the entire string to the console.
- println("Result: " + test(2, 2)): Similar to the previous line, this calls the "test ()" function with arguments 2 and 2, concatenates the result with the string "Result: ", and prints the entire string to the console.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Print "Hello, world" and version of the Scala language.
Next: Absolute difference between n and 51. If n is greater than 51 return triple the absolute difference.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/basic/scala-basic-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics