w3resource

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


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


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should be familiar with the following concepts:

  • Sum of Numbers: The sum of numbers from 1 to n is the result of adding all integers from 1 up to n. This is a common problem in mathematics and programming.
  • Tail Recursion: A tail-recursive function is one in which the recursive call is the last operation performed in the function. Tail recursion is efficient because it avoids adding extra stack frames, making it more suitable for large inputs.
  • Accumulator: An accumulator is a variable used to accumulate results in recursive functions. In this case, it tracks the running sum of numbers as the recursion progresses.
  • Base Case: A base case in recursion defines when the function should stop. For the sum of numbers, the base case is when the number (n) becomes 0.
  • Recursive Case: In this case, the recursive case subtracts 1 from n and adds the current value of n to the accumulated sum.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Write the basic recursive function that calculates the sum of numbers from 1 to n without worrying about tail recursion.
  • Hint 2: Add an accumulator parameter to keep track of the running sum.
  • Hint 3: In each recursive call, subtract 1 from n and add it to the current sum.
  • Hint 4: Use the base case to stop recursion when n becomes 0 and return the accumulated sum.
  • Hint 5: Make sure to use the tailrec modifier to optimize the recursion for large inputs and avoid stack overflow errors.

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.