204k views
0 votes
Write the recursive method printNumber. The public static method named printNumber takes two parameters. The first parameter is an integer array called nums, and the second is parameter is an even int called index. The return value is an integer that is the product of the even index values in nums whose index is less than or equal to index. Assume that the array nums has length >

User RidRoid
by
4.8k points

1 Answer

1 vote

Answer:

The function is as follows:

public static void printNumber(int nums[],int index){

if (index < 0) {

System.out.print(nums[0]);

return; }

if (index % 2 == 0){

if(index!=0){

nums[index-2]*=nums[index];} }

printNumber(nums, index - 1);

}

Step-by-step explanation:

To do this, we need to save the required product in the 0 index element of the array.

This defines the function

public static void printNumber(int nums[],int index){

If the index variable < 0,

if (index < 0) {

Print the 0 index as the product [i.e. the calculated product]

System.out.print(nums[0]);

This ends the recursion

return; }

If the current array index is even

if (index % 2 == 0){

Check if index is not 0

if(index!=0){

If both conditions are valid, calculate the product and save the result in index - 2 element. The final result is then saved in the 0 index

nums[index-2]*=nums[index];} }

Call the function while the base case has not been executed

printNumber(nums, index - 1);

}

User KeshavDulal
by
4.7k points