...

/

Solution Review: Average of Numbers

Solution Review: Average of Numbers

This review provides a detailed analysis of the solution to find the average of numbers.

We'll cover the following...

Solution: Using Recursion

Press + to interact
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 of an array containing only 11 number, is the number itself. This condition can be our base case.

averageofarrayoflength1=a01=a0\displaystyle ...