# Coding short program

Recursion

The purpose of this lab is to become familiar with the use of recursion in computation.

1. Implement the recursive factorial function given below (from the lecture notes on recursion). Develop a main program that allows the user to enter any integer (positive) integer value, and displays the factorial of that value. The program should allow the user to either keep entering another value, or quit the program.

public static int factorial(int n) {

if (n == 0) return (1);

else
return (n * factorial(n-1));

}
2. Determine the largest value for n that can be correctly computed.

3. Implement the recursive Towers of Hanoi function given below (from the lecture notes). Develop a main program that allows the user to enter any number of disks to solve.

public static void towers(int numDisks,
String startPeg, String destPeg, String sparePeg)

{
if (numDisks == 1)

System.out.println(“Move disk from ” + startPeg + ” to ” + destPeg); else

{
towers(numDisks-1, startPeg, sparePeg, destPeg); System.out.println(“Move disk from ” + startPeg + ” to ” + destPeg); towers(numDisks-1, sparePeg, destPeg, startPeg);

} }

4. Modify function towers so that all the print statements are disabled (i.e., comment them out). There needs to be a statement after if(numDisks …), so replace that with just numDisks = numDisks. (The compiler will actually remove this pointless statement.)

Modify the main program so that “Starting towers …” is displayed right before the function is called, and “Finished towers” when completed (right after the function call). Run your program using this new version of the function (that does not display the moves) to determine how long it takes to complete for the following number of disks: 10, 20, 30, 32, 34, 36. Use your smart phone to determine each execution time to the nearest second.

Typ to your responses to questions 2 and 4 in the comments box when submitting.