just trying to find the sum in the array and can't figure out what is wrong with my code, if you can help that would be appreciated :)
function arraySum(arr, index) {
if (arr.length <= index)
return 0;
return (arraySum(arr, arr.length - 1) arr[arr.length - 1]);
}
I'm trying to find the sum of the array using recursion. what is exactly wrong with my code :) if you can help that would be appreciated
ps index=0 arr.length =8
CodePudding user response:
First of all, in the recursion patterns you need a break condition.
Second, in each step of the recursion you need to take a little piece of work, and pass the rest to the others.
You have the break condition but it seems like your little piece of work is missing or not done properly.
Here is how to do that:
var sum = function(arr, currentIndex) {
if(currentIndex < 0 || currentIndex >= arr.length) return 0;
return arr[currentIndex] sum(arr, currentIndex);
};
//Test it
var arr = [1, 4, 5];
sum(arr, 0);
CodePudding user response:
Note: There are much better ways of achieving the desired goal:
Since this is a simple array if you just need sum you can use reduce method
function sum(arr) {
const reducer = (sum, val) => sum val;
const initialValue = 0;
return arr.reduce(reducer, initialValue);
}
sum([1, 3, 5, 7]); // 16
CodePudding user response:
function findSum(A, N) {
if (N <= 0)
return 0;
return (findSum(A, N - 1) A[N - 1]);
}
let A = [1, 2, 3, 4, 5];
let N = A.length;
document.write(findSum(A,N));