Home Tutorial Java Core Multiply a range of array elements using Recursion

 
 

Multiply a range of array elements using Recursion
Posted on: June 16, 2010 at 12:00 AM
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
Advertisement

Related Tags for Multiply a range of array elements using Recursion:


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.

Posted on: June 16, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com