Kotlin Program: Lambda expression to check if a number is even
Kotlin Lambda: Exercise-3 with Solution
Write a Kotlin program that implements a lambda expression to check if a number is even.
Sample Solution:
Kotlin Code:
fun main() {
val isEven: (Int) -> Boolean = { num -> num % 2 == 0 }
val number = 8
//val number = 7
val result = isEven(number)
println("$number is even: $result")
}
Sample Output:
8 is even: true 7 is even: false
Explanation:
In the above exercise -
First we declare a lambda expression isEven of type (Int) -> Boolean, which takes an integer num as an input parameter and checks if it is even by using the condition num % 2 == 0. If the number is even, the lambda expression returns true, otherwise it returns false.
Inside the "main()" function, we define a number "number". We then invoke the isEven lambda expression by passing "number" as an argument and store the result in the result variable. The result is then printed using println.
Kotlin Editor:
Previous: Lambda expression for finding the square of a number.
Next: Lambda expression for calculating the average of 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/lambda/kotlin-lambda-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics