Share on Google+Share on Google+

Multiply a range of array elements using Recursion

Advertisement
In this section, you will learn how to multiply a range of array elements using recursion.

Multiply a range of array elements using Recursion

In this section you will learn how to use recursion to multiply a range of array elements. For this we have created a method rangeMult() that takes three arguments: an int array that contains the range of elements to be multiplied, an int specifying the starting element of the range, and an int specifying the ending element of the range. The program will return the product of the array elements that are within the range.

Here is the code:

class RecursionMethod {
	public static int rangeMult(int num[], int start, int end) {
		if (start > end) {
			return 1;
		} else {
			return num[start] * rangeMult(num, start + 1, end);
		}
	}

	public static void main(String[] args) {
		int[] num = { 1, 2, 3, 4, 5 };
		int result = RecursionMethod.rangeMult(num, 0, 2);
		System.out.println(result);
	}
}

Output

6

Advertisements

Posted on: June 16, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.