Base case (Termination condition) : if n == 0 then return 0
General case : return the sum of the first n-1 integers in the array plus the value at the specified index in the array
For the input array {1, 3, 5, 4, 7} find the sum of the first 4 items in the array recursively.
Result is the sum of the items = 1+3+5+4=13
public class SumOfNIntegers { public static int recursiveArraySum(int[] data, int n) { if( n==0 ) return 0; else return recursiveArraySum(data, n-1) + data[n-1]; } public static void main(String[] args) { int[] inputArray = {1, 3, 5, 4, 7}; int result = recursiveArraySum(inputArray, 3); System.out.println(result); result = recursiveArraySum(inputArray, 4); System.out.println(result); } }recursiveArraySum method takes input array and the number of items to sum from the beginning of the array.
Console output is :
9
13
Diagram for the recursive method calls :
Reference : http://www.amazon.com/Data-Structures-Algorithms-Java-Edition-ebook/dp/B00JDRQF8C
No comments:
Post a Comment