Choices
Exercise 1: Even Odd
Write a program that takes an integer input and prints whether it is even or odd.
Exercise 2: Larger
Write a program that takes two integers as input and prints the larger of the two.
Exercise 3: Maximum
Write a program that takes three integers as input and prints the largest of the three.
Exercise 4: Vowel or Consonant
Write a program that takes a character input and prints whether it is a vowel or a consonant.
In this example, we use the match expression to match the input character against a set of patterns to check if it is a vowel or consonant We use the match to return a 'Vowel' or a 'Consonant'.
Exercise 5: Weekend
Write a program that takes a day of the week as input and prints whether it is a weekday or a weekend day.
In this example, we use the match expression to match the input day against multiple patterns. If the input is "Saturday" or "Sunday", the code in the first block will execute and return "Weekend". Otherwise, the code in the last block will execute and return "Weekday".
Exercise 6: Number name
Write a program that takes an integer input and prints its English name. For example, if the input is 2, the program should print "two".
Solutions
Exercise 1: Even Odd
val x: Int = 10
val result =
if x % 2 == 0 then "Even"
else "Odd"
println(result)
Exercise 2: Larger
val x: Int = 10
val y: Int = 20
val larger: Int = if x > y then x else y
println(s"The larger number is $larger.")
Exercise 3: Maximum
val x: Int = 10
val y: Int = 20
val z: Int = 15
val largest: Int = if x > y && x > z then
x
else if y > z then
y
else
z
println(s"The largest number is $largest.")
Exercise 4: Vowel or Consonant
val ch: Char = 'a'
val result: String = ch match
case 'a' | 'e' | 'i' | 'o' | 'u' => "Vowel"
case _ => "Consonant"
println(result)
Exercise 5: Weekend
val day: String = "Saturday"
val result: String = day match
case "Saturday" | "Sunday" => "Weekend"
case _ => "Weekday"
println(result)
Exercise 6: Number name
val x: Int = 4
val result: String = x match
case 1 => "one"
case 2 => "two"
case 3 => "three"
case 4 => "four"
case 5 => "five"
case 6 => "six"
case 7 => "seven"
case 8 => "eight"
case 9 => "nine"
case _ => "invalid"
println(result)