Kotlin recursive function: Calculate the sum of array elements
Kotlin Function: Exercise-3 with Solution
Write a Kotlin recursive function to calculate the sum of elements in an array.
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.
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://w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics