Kotlin Function: Print even numbers from list, Return Unit
Write a Kotlin function that takes a list of integers as an argument and prints only the even numbers in the list. The function should return Unit.
Pre-Knowledge (Before you start!)
- Basic Kotlin Syntax: Familiarity with writing and running Kotlin programs.
- Kotlin Functions: Understanding how to define and call functions in Kotlin.
- Unit Type: Awareness that functions without a return value implicitly return Unit in Kotlin.
- Lists in Kotlin: Knowledge of working with lists, including iterating through elements.
- Modulo Operator: Understanding the modulo operator (%) to check if a number is even or odd.
- Conditional Statements: Ability to use if statements to filter elements based on conditions.
- Printing Output: Familiarity with the println() function to display output on the screen.
Hints (Try before looking at the solution!)
- Define the Function.
- Iterate Through the List.
- Check for Even Numbers.
- Print Even Numbers.
- Call the Function.
- Test with Different Lists.
- Common Errors to Avoid:
- Forgetting the modulo operator.
- Misplacing if conditions.
- Unnecessarily adding a return statement.
Sample Solution:
Kotlin Code:
fun printEvenNumbers(numbers: List<Int>): Unit {
for (number in numbers) {
if (number % 2 == 0) {
println(number)
}
}
}
fun main() {
val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14)
printEvenNumbers(numberList)
}
Sample Output:
2 4 6 8 10 12 14
Explanation:
In the above exercise -
The "printEvenNumbers()" function receives a 'numbers' parameter of type List
In the "main()" function, a sample number list (numberList) is provided, and "printEvenNumbers()" function is called with this list as an argument. The function then prints only the even numbers in the list.
Kotlin Editor:
Previous: Print numbers from 1 to n, Return Unit.
Next: Check if the number is negative.
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