Carlos Luis
Carlos Luis

Reputation: 213

Find the sum of array elements recursively

i have the following school assignment: public static double sum(double [] a, int low, int high)

that returns the sum of all numbers in the array slice a[low:high].

If low > high, it throws an IllegalArgumentException. Otherwise, it checks if the slice has 1 item. If so, it returns that value.

If the slice has 2 or more items, it divides the slice into 2 equal subslices, computes the sums of the 2 subslices and returns the sum of the 2 partial sums. This is what i wrotte: Iam really bad with recursion, and this is like the first recursive code i writte.

public static  double sum(double [] a, int low, int high) throws Exception{
    if(low > high){
        throw new IllegalArgumentException();
    }
    else if(low == high){
        return a[low];  
    }   
    return sum(a, low, high/2) + sum(a, high/2, high);
}

how far am i from an answer? UPDATE: This is all the code iam executing:

public class ArraySum {
    int low; 
    int high;
    double []list;


    public ArraySum(int lowIn, int highIn, double []listIn){
        low = lowIn;
        high = highIn;
        list = listIn;  
    }
    public double auxSum() throws Exception{
        return sum(list, low, high);
    }
    public static  double sum(double [] a, int low, int high) throws Exception{
        if(low > high){
            throw new IllegalArgumentException();
        }
        else if(low == high){
            return a[low];  
        }   
        return sum(a, low, (high+low)/2) + sum(a, (high+(low+1))/2, high);
    }
}

and this is my Main:

public class Main {

    public static void main(String[] args) throws Exception {
        double [] l = {1,2,3,4,5};
        ArraySum a = new ArraySum(0, 5, l);
        System.out.println("the sum is: " + a.auxSum());

    }
}

Upvotes: 1

Views: 1098

Answers (1)

aioobe
aioobe

Reputation: 421280

You almost got it! Here are a few pointers:

  • high/2 isn't really right. (Think about what happens if you have low = 98 and high = 100.)

  • When you recurse you need to keep in mind that the indexes you pass are inclusive, so in the second recursive call I suggest you add 1 to the lower index (so that it doesn't overlap with the upper index of the first recursive call)

Let me know if you want me to clarify either item.

Upvotes: 2

Related Questions