Thursday, October 2, 2014

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;

/**
* Author: <<Conrado Sanchez>> Date: Task:
*/
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







No comments:

Post a Comment