Multiply a range of array elements using Recursion


 

Multiply a range of array elements using Recursion

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

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

Ads