# Thread: Problem Understanding RECURSIVE METHODS

1. Member
Join Date
Oct 2013
Posts
63
Rep Power
0

## Problem Understanding RECURSIVE METHODS

I'm trying to understand the concept behind this recursive method called rangeSum. This method sums a range of array elements with recursion. I tried summing the elements of 2 through 5, and I tried writing down what actually happens when java executes the program, but what I get when I try to figure it out by paper is different from what netbeans gives me. Here is a snapshot of my scratch work as well as my source code. Netbeans gives me "The sum of elements 2 through 5 is 18" when I try running it but it I get 12 when I do the recursion on paper. I know that the source code is correct because it's out of the book but what am I doing wrong when I try figuring it out by hand?

XML Code:
```package recursivecall;

import java.util.Scanner;

/**
*/
public class RecursiveCall {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("The sum of elements 2 through 5 is " + rangeSum(numbers, 2, 5));

} // end of main()

/**
* The rangeSum method calculates the sum of a specified range of elements
* in array.
* @param start Specifies the starting element.
* @para end Specifies the ending element.
* @return The sum of the range.
*/
private static int rangeSum(int[] array, int start, int end) {
// base case
if (start > end) {
return 0;
} else {
return array[start] + rangeSum(array, start + 1, end);
}
}

} // end of RecursiveCall class```
Last edited by csanch11; 10-03-2014 at 06:49 AM.

2. Moderator
Join Date
Apr 2009
Posts
13,541
Rep Power
27

## Re: Problem Understanding RECURSIVE METHODS

That last bit is wrong, since 5 is not > 5.
So it will return the value in array[6] and then go once more into rangeSum(6), so 6 > 5 and return 0.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•