Question: In Java a function can call itself (we may explore more about this later in the course). This is called a recursive function. In order

 In Java a function can call itself (we may explore more

In Java a function can call itself (we may explore more about this later in the course). This is called a "recursive function". In order for this to work there must be a situation where the function finally stops calling itself and simply returns a value (or just returns). We can use a Java if statement to make a recursive function return as required to make it work properly. This special case where the function finally returns is called the recursive function base case. Here is a simple example: a function to calculate the factorial of an integer number n >= 1. Remember that the factorial of n, n! is no(n-1)(n-2).....1 if n is greater than or equal to 1. Factorial's base case occurs when n is 1 the function should then return 1; otherwise the function returns no(n-1)! by definition, n! is no(n-1)! if n > 1. Here's a Java recursive factorial function implementation, assuming n is at least 1: public static long factorial(int n) // header line: Long return value since factorials grow rapidly! if (n == 1) // this tests to see if n is 1, the base case return 1; // if so, the function returns 1 return n*factorial(n-1); // assumes n >= 1 // otherwise a recursive call - factorial calls itself! // this second return executes if the if condition is false Your job for this part of the Lab is to create and test a similar recursive function that calculates and returns an integer power p of some integer number n; n and p are the parameters to the function, with header line static long power(int n, int p). You can assume that p is at least 0. Modify the above factorial function as follows: Update the header line for the function as above and then make these changes: The base case for the power function occurs when p is 0, at which point the function returns the value 1 (by definition, any number raised to the 0 power is 1). To test for O, the base case, replace the if condition with this one: if (p == 0). If p is not 0 then the function should return n*power(n, p-1) no is n:n(p-1) if p is greater than 0. Use that information to change the second return statement. Now test to make sure power works by having main call it with some known values and print out the results. For example, power(3, 2) should return 32 = 9, power(-2, 7) should return (-2) = -128, and power(8,0) should return 1. Derive Power.java from Factorial.java, and modify main to test power

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!