C# Recursion SumOfOnlyNeg Elements
Posted
by Chris
on Stack Overflow
See other posts from Stack Overflow
or by Chris
Published on 2010-05-26T07:26:09Z
Indexed on
2010/05/26
7:31 UTC
Read the original article
Hit count: 223
c#
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.
}
}
© Stack Overflow or respective owner