Here’s a short practice exercise in Scala:
- Write a program that takes an integer as input and prints whether the integer is even or odd:
scalaCopy codeimport scala.io.StdIn
object EvenOrOdd {
def main(args: Array[String]): Unit = {
val input = StdIn.readInt()
if (input % 2 == 0) {
println("Even")
} else {
println("Odd")
}
}
}
- Write a function that takes an integer as input and returns the sum of all the even numbers from 1 to the input value:
scalaCopy codedef sumOfEvens(n: Int): Int = {
(2 to n).filter(_ % 2 == 0).sum
}
// Example usage:
val result = sumOfEvens(10)
println(result) // Output: 30
- Write a program that reads in a list of integers from the console and prints the average of the values:
scalaCopy codeimport scala.io.StdIn
object Average {
def main(args: Array[String]): Unit = {
val input = StdIn.readLine()
val numbers = input.split(" ").map(_.toInt)
val sum = numbers.sum
val average = sum.toDouble / numbers.length
println(f"Average: $average%.2f")
}
}
- Write a recursive function that calculates the factorial of a given number:
scalaCopy codedef factorial(n: Int): Int = {
if (n == 0) {
1
} else {
n * factorial(n - 1)
}
}
// Example usage:
val result = factorial(5)
println(result) // Output: 120
These exercises should give you a taste of some of the basic features of Scala. As you become more familiar with the language, you can try more advanced exercises that make use of Scala’s functional programming features, such as higher-order functions and immutable data structures.