w3resource

Kotlin recursive function: Calculate the sum of array elements


Write a Kotlin recursive function to calculate the sum of elements in an array.


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should understand these concepts:

  • Recursion: Recursion is a programming technique where a function calls itself to solve a problem by breaking it into smaller subproblems.
  • Base Case in Recursion: A base case is required to stop recursion. In this problem, when the index reaches the array size, we return 0.
  • Recursive Case: The function should add the current element of the array to the result of the function called with the next index.
  • Array Indexing: Arrays in Kotlin use zero-based indexing, meaning the first element is at index 0.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Define a function that takes an array and an index as parameters.
  • Hint 2: Use an if condition to check if the index has reached the array size (base case).
  • Hint 3: If the index is within bounds, add the current element to the sum of the remaining elements using recursion.
  • Hint 4: Continue recursion until all elements are summed, then return the computed total.

Sample Solution:

Kotlin Code:

fun calculateSum(array: IntArray, index: Int = 0): Int {
    return if (index == array.size) {
        0
    } else {
        array[index] + calculateSum(array, index + 1)
    }
}

fun main() {
    val array = intArrayOf(1, 2, 3, 4, 5, 6, 7)
    val sum = calculateSum(array)
    println("Sum of elements in the array: $sum")
}

Sample Output:

Sum of elements in the array: 28

Explanation:

In the "calculateSum()" function, we pass the array and an initial index of 0. At each recursive call, we check if the index is equal to the array size. If it is, we return 0 since there are no more elements to add. Otherwise, we add the element at the current index to the sum of the remaining elements. This is obtained by recursively calling the "calculateSum()" function with the incremented index. This process continues until we reach the end of the array, and we eventually get the sum of all elements.

When we run the program with the given array [1, 2, 3, 4, 5, 6, 7], it will calculate and print the sum of all elements in the array, which is 28.

Kotlin Editor:


Previous: Calculate the power of a number.
Next: Find the smallest element in an array.

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.