w3resource

Kotlin Function: Print even numbers from list, Return Unit

Kotlin Function: Exercise-13 with Solution

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.

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, representing a list of integers. It iterates through each number in the list and checks if it is even. It uses the modulus operator % to determine if the number divided by 2 has a remainder of 0. If a number is even, it is printed using the "println()" function.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/function/kotlin-function-exercise-13.php