Greetings,

I have a array filled up with random value's (being positive and negative).

What i wanne do is have a recursive version that counts -only- counts the postive values in that array.

Recu version that counts all the elements (that works but is not quite yet what i seek)

``````public int RecSumAllElem(int[] table, int n)
{
if (n == 1)
return table[0];
else
{
return (table[n - 1] + RecSumAllElem(table, n - 1));
}

}``````

Next is my attempt to only count the +'s values in the array.
But no mather what i try to change it keeps generating wrong output.
(Sometimes it generates the proper output, but overall it usally always wrong (especially when the array holds many values).

For example the array: [10, -5, 5, -6; -9] should generate the sum of 15.

``````public int RecSumPosElem(int[] table, int n)
{
if (n == 1)
return table[0]; //stopCriterium
else
{
if (table[n - 1] > 0)
return (table[n - 1] + RecSumPosElem(table, n - 1));
else
return RecSumPosElem(table, n - 1);
}

}``````

Regards.

Try something like this

``````static int GetSumOfPositiveValues(int[] array, int index)
{
int sum = 0;

if (index < array.Length - 1)
sum += GetSumOfPositiveValues(array, index + 1);

if (array[index] > 0)
sum += array[index];

return sum;
}

..

int[] array = { 10, -5, 5, -6, -9 };
int positiveSum = GetSumOfPositiveValues(array, 0);``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.