w3resource

Kotlin Tail-Recursive Function: Sum of numbers from 1 to n

Kotlin Function: Exercise-15 with Solution

Write a Kotlin tail-recursive function to calculate the sum of all numbers from 1 to n.

Sample Solution:

Kotlin Code:

tailrec fun sumNumbers(n: Int, currentSum: Int = 0): Int {
    if (n == 0) {
        return currentSum
    }
    
    return sumNumbers(n - 1, currentSum + n)
}
 
fun main() {
    val n = 7
    val sum = sumNumbers(n)
    println("Sum of numbers from 1 to $n: $sum")
}

Sample Output:

Sum of numbers from 1 to 7: 28

Explanation:

In the above exercise -

  • The "sumNumbers()" function takes two parameters: n, which represents the number up to which we want to calculate the sum, and currentSum, which keeps track of the running sum.
  • In the base case, if n becomes 0, it means we have reached the end and return the current sum.
  • In each recursive call, we decrement n by 1 and add it to the current sum (currentSum + n).
  • We use tail recursion by making the recursive call directly without additional computation.
  • The recursive calls continue until the base case is reached and the final sum is computed.

Kotlin Editor:


Previous: Calculate factorial.
Next: Calculate the nth Fibonacci.

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.