w3resource

Kotlin Function: Print even numbers from an array

Kotlin Function: Exercise-2 with Solution

Write a Kotlin function that takes an array of integers and prints only even numbers.

Sample Solution:

Kotlin Code:

fun printEvenNumbers(numbers: IntArray) {
    println("Even numbers:")
    for (number in numbers) {
        if (number % 2 == 0) {
            println(number)
        }
    }
}

fun main() {
    val numbers = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    printEvenNumbers(numbers)
}

Sample Output:

Even numbers:
2
4
6
8
10

Explanation:

In the above exercise -

  • The "printEvenNumbers()" function takes an array of integers "numbers" as an argument. It iterates over each array element using a for loop. Inside the loop, it checks if the current number is even by using the modulo operator %. If the remainder is 0, it means the number is even, so it is printed using println() function.
  • In the "main()" function, we create an array of integers named numbers and initialize it with some values. Then, we call the printEvenNumbers function and pass the numbers array as an argument.

Kotlin Editor:


Previous: Personalized greeting message for user.
Next: Count vowels in a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.