Kotlin program: Check if a number is even or odd
Write a Kotlin program to check if a given number is even or odd.
Pre-Knowledge (Before you start!)
- Basic Kotlin Syntax.
- Kotlin Functions.
- Command-Line Arguments.
- Type Conversion.
- Conditional Statements.
- Modulo Operator.
- String Interpolation.
- Error Handling.
Hints (Try before looking at the solution!)
- Define the main() Function.
- Check for Input.
- Convert Input to Number.
- Validate Conversion.
- Check Even or Odd.
- Handle Invalid Input.
- Handle Missing Input.
- Test with Different Inputs.
- Common Errors to Avoid:
- Forgetting to check if args is empty.
- Not handling invalid inputs properly.
- Misplacing operators or parentheses.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics