Kotlin program: Check if a number is even or odd
Kotlin Basic: Exercise-6 with Solution
Write a Kotlin program to check if a given number is even or odd.
Sample Solution:
Kotlin Code:
fun main(args: Array<String>) {
if (args.isNotEmpty()) {
val number = args[0].toIntOrNull()
if (number != null) {
if (number % 2 == 0) {
println("$number is even.")
} else {
println("$number is odd.")
}
} else {
println("Invalid input. Please enter a valid number.")
}
} else {
println("No input provided. Please provide a number as a command-line argument.")
}
}
Sample Output:
12 is even.
17 is odd.
Explanation:
In the above exercise -
- Inside the "main()" function, a variable named number is declared and assigned a value of 12.
- The if statement is used to check whether number is divisible evenly by 2. The expression number % 2 calculates the remainder when number is divided by 2. If the remainder is 0, it means the number is even.
- If the condition number % 2 == 0 evaluates to true, the code block inside the if statement executes. In this case, it prints the message "$number is even." using string interpolation, where $number is replaced by the actual value of number.
- If the condition number % 2 == 0 evaluates to false, the code block inside the else statement executes. In this case, it prints the message "$number is odd." using string interpolation, where $number is replaced by the actual value of number.
Kotlin Editor:
Previous: Arithmetic operations on two numbers.
Next: Find maximum and minimum of three numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/kotlin-exercises/basic/kotlin-basic-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics