w3resource

Kotlin recursive function: Sum of even numbers in a range

Kotlin Function: Exercise-13 with Solution

Write a Kotlin recursive function to calculate the sum of all even numbers in a range.

Sample Solution:

Kotlin Code:

fun sumEvenNumbers(start: Int, end: Int): Int {
    if (start > end) {
        return 0
    }
    
    return if (start % 2 == 0) {
        start + sumEvenNumbers(start + 2, end)
    } else {
        sumEvenNumbers(start + 1, end)
    }
}
 
 fun main() {
    val start = 10
    val end = 30
    val sum = sumEvenNumbers(start, end)
    println("Sum of even numbers from $start to $end: $sum")
}

Sample Output:

Sum of even numbers from 10 to 30: 220

Explanation:

In the above exercise -

  • The function "sumEvenNumbers()" takes two parameters: start and end, representing the range of numbers to consider.
  • In the base case, if start is greater than end, it means we have reached the end of the range, so we return 0.
  • If start is an even number (start % 2 == 0), we add it to the sum of the remaining even numbers in the range. We recursively call the "sumEvenNumbers()" function with start + 2 to consider the next even number.
  • If start is an odd number, we skip it and move to the next number by recursively calling the "sumEvenNumbers()" function with start + 1.
  • The recursive calls continue until the base case is reached and the final sum is computed.

Kotlin Editor:


Previous: Binary tree as a binary search tree.
Next: Calculate factorial.

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