Scala control flow program to check even or odd number
Write a Scala program to check if a given number is even or odd using if/else statements.
Sample Solution:
Scala Code:
object EvenOddChecker {
def main(args: Array[String]): Unit = {
//val number: Int = 15 // Number you want to check
val number: Int = 20 // Number you want to check
if (number % 2 == 0) {
println(s"The number $number is even.")
} else {
println(s"The number $number is odd.")
}
}
}
Sample Output:
The number 15 is odd.
The number 20 is even.
Explanation:
First we define a variable "number" and assign it a value to check. We use the modulo operator % to check if the remainder of "number" divided by 2 is equal to 0. If the remainder is 0, it means the number is divisible by 2 and hence even. In that case, we print "The number is even." If the remainder is not 0, it means the number is not divisible by 2 and hence odd. In that case, we print "The number is odd."
Scala Code Editor :
Previous: Find the maximum of two numbers.
Next: Find a factorial with a while loop.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics