Search⌘ K
AI Features

Solution Review: Average of Numbers

Explore how to solve the problem of finding the average of numbers in an array using recursion. Understand setting a base case for arrays of length one and how recursive calls accumulate sums before dividing by array length. This lesson guides you through the step-by-step logic and function call sequence, helping you apply recursion effectively to array-based problems.

We'll cover the following...

Solution: Using Recursion

Javascript (babel-node)
function average(testVariable, currentIndex = 0) {
// Base Case
if (currentIndex == testVariable.length - 1) {
return testVariable[currentIndex]
}
// Recursive case1
// When currentIndex is 0
if (currentIndex == 0) {
return ((testVariable[currentIndex] + average(testVariable, currentIndex + 1)) / testVariable.length)
}
// Recursive case2
// Compute sum
return (testVariable[currentIndex] + average(testVariable, currentIndex + 1))
}
// Driver code
array = [10, 2, 3, 4, 8, 0]
console.log(average(array))

Explanation

The average ...