David Dredd de Jesus
David Dredd de Jesus

Reputation: 23

JAVA: Addition from start to end using recursion

I need help with this recursion method. I need it to add the integers from a starting point up to the end point.

    public static int sumInts(int begin, int end){
    if (begin == end)
        return begin + end;
    else
        return sumInts(begin+1,end);
}

Example output should be: Start: 1 End: 4 Sum is: 10

But I'm getting 8 as my output for those particular input. I know it's the condition that's ruining this but I can't seem to figure it out..

Upvotes: 1

Views: 929

Answers (1)

BackSlash
BackSlash

Reputation: 22243

But I'm getting 8 as my output for those particular input.

It's normal. It will go to the else block everytime but the last time, because both begin and end will be 4 and it will return 4 + 4 = 8.

You should do something like this:

public static int sumInts(int begin, int end){
    if (begin == end)
        return end; // return the last number
    else
        return begin + sumInts(begin+1,end); // sum the current number with the recursion result
}

And this can of course be done the other way - by decreasing end instead of increasing begin.

public static int sumInts(int begin, int end){
    if (begin == end)
        return begin;
    else
        return end + sumInts(begin,end-1);
}

Upvotes: 7

Related Questions