C# Recursion SumOfOnlyNeg Elements
- by Chris
Hello,
A array gets filled up with random elements (negative and positive).
Now i want to calculate the sum of ONLY the postive elements.
Iterative there is no problem, but in the recursion version i can only get the sum of both negative and postive.
How can i "check" in the recursive version that it only sums up the Postive elements?
Best Regards.
Iterative version:
public int IterSomPosElem(int[] tabel, int n)
{
n = 0;
for (int i = 0; i < tabel.Length; i++)
{
if (tabel[i] >= 0)
{
n += tabel[i];
}
}
return n;
}
Recursive version atm (sums up all the elements insteed, of only the positive)
public int RecuSomPosElem(int[] tabel, int n)
{
if(n == 1)
return tabel[0]; //stopCriterium
else
{
return (tabel[n - 1] + RecuSomPosElem(tabel, n - 1)); // how to check, so it only sums up the postive elements and "ignores" the negative elements.
}
}