I have a problem with a function, using recursion. It's a bit difficult and long to explain it as it is, so I will try to write just the essentials and give some pseudocode. Hope it's understandable enough.
Lets say I have an array of numbers - the positive ones should be added to a given number, while if there are negative numbers, their absolute value tells from which position of the array to start adding the next possitive numbers.
Example:
The given number is 5.
array = [1, 2, -3, 5, 7, 8, 9]
0 1 2 3 4 5 6 <------- positions
So we have: 5(it is given) + 1+2 + (array[from 3th element] = 5+7+8+9) = 5 + 3 + 29 = 37
and I have (lets say that the body of the function have access and changes the variable named number):
number = 5;
sum(array)
{
for each element from first to last in the array {
//here i have some other actions, saving some states
if (element < 0) {
return sum(array[abs(element) to end])
}
number += element
}
}
Can you please give me some idea or directions how to remove the recursion?
PS: Sorry and please excuse me if the question is too general or not understandable, if it is such I will delete it as soon as possible.
5 + 3 + 29from...?return number + sum(array[abs(element) to end])?