tags:

views:

68

answers:

6

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.
        }

    }
A: 
int recsum(int[] nums, int n)
{
   if (n == -1)
       return 0;
   else 
   {
        int sum = recsum(nums, n-1);
        if (nums[n] > 0)
           sum += nums[n];
        return sum;
   }
}
Hasan Khan
A: 

Something like?

public int RecuSomPosElem(int[] tabel, int n) 
    { 
        if(n == 1) 
            return tabel[0]; //stopCriterium 
        else 
        { 
            var valueToSum = tabel[n - 1] > 0 ? tabel[n - 1] : 0;
            return (valueToSum + RecuSomPosElem(tabel, n - 1)); 
        } 

    } 
Daniel Elliott
A: 
public int RecuSomPosElem(int[] tabel, int n)
{
    if(n == 1)
        return tabel[0]; //stopCriterium
    else
    {

        if (tabel[n - 1] > 0)
            return (tabel[n - 1] + RecuSomPosElem(tabel, n - 1)); 
        else
            return RecuSomPosElem(tabel, n - 1));
    }

}
IVlad
+1  A: 

Is this homework? Why do you need to do this with a recursive function?

In the real world, it would be some simple LINQ

int positiveSum = tabel.Where(i => i > 0).Sum();
Jamiec
Because homework isn't about the real world - most straight-from-school-coders can't actually code -and they don't need to-, but they should know basic stuff like recursion.
riffnl
@riffnl - Hence why I asked if this was homework.
Jamiec
+1  A: 

How about

int foo[] = new [] {1, -9, 10, 8, -16, ...};
int sumOfPostiveInts = foo.Sum(x => x < 0 ? 0 : x);

or...foo.Where(x => x > 0).Sum();
Rob
A: 

You're so close! Using your algorithm, but just adding a check to see if the current value in table is negative or not. If it is negative move on to the next array item:

    private static int RecuSomPosElem(int[] tabel, int n)
    {
        int i = n - 1;
        while (tabel[i] < 0 && i > 0)
            i--;
        if (i == 0)
        {
            return 0; //stopCriterium 
        }
        else
        {
            return (tabel[i] + RecuSomPosElem(tabel, i));
        }
    } 
Phil