Home > Software engineering >  Recursion method that finds the sum between two numbers
Recursion method that finds the sum between two numbers

Time:01-29

I want to implement a recursive method that finds the sum of x consecutive integers, starting from a starting number and ending with an end number.

For example, if start = 0 and end = 3, the method returns 6 (0 1 2 3). I tried to come up with the right code but I'm new to recursion and I couldn't find the right base case.

public static int summation(int start, int end) {
        if (start == end) {
            return 0;
        }
        else {
            return  summation(end, end - 1);
        }
}

CodePudding user response:

This works but make sure that start is less than end.

public static int summation(int start, int end) {
    if(start < end) return start   summation(start   1, end);
    else return end;
}

If you want to use the method to calculate sum between start and end even if start > end, then use this code:

public static int summation(int start, int end) {
    if(start < end) return start   summation(start   1, end);
    else if(start > end) {
        start  = end;
        end = start - end;
        start -= end;
        return summation(start, end);
    }
    else return end;
}
  •  Tags:  
  • Related