Week 6

Post date: Feb 10, 2019 4:54:13 AM

Chapter 5 Recursion:

    • Recursive Definitions,

    • Method Calls,

    • Tail Recursion

Lab 6 – Recursion I

Objectives:

Learn How to Implement Recursive Methods

Examples:

1- TestFactorial: Shows the recursive Factorial method discussed in lecture

2- TestFibonacci: Shows the recursive Fibonacci method discussed in lecture

3- TestPower: Shows the recursive Power method discussed in lecture

4- TestPrintReverse: Shows the recursive PrintReverse method discussed in lecture

5- TestAddArray: Shows the recusive AddArray method discussed in lecture

6- TestPrintOdds: Shows the recursive methods to print odd numbers (forward and backward)

Tasks:

(1)(a) Write a program that reads an integer n from the user and then print all even numbers between 0 to n. Your program must include a recursive method:

public static void recursivePrintEvens(int n), that does the printing.

(b) Update your program by adding a method,

public static void recursiveReversePrintEvens(int n), that uses recursion to print the even numbers in reverse order. Update the main method to test this method.

(2) Write a recursive method, public static int multiply(int n, int m), that computes and returns the result of multiplying m and n without using the multiplication operator ‘*’. Test your method by calling it in a main method with actual values for m and n.

(3) Write a recursive method to find the minimum element in an array of integers. Test your method by writing a main method that initializes an array with integer values and then calls your method to find the minimum and print it.

Hint: Similar to AddArray, you need to have an overloaded version of your method to provide the initial index.

(4) One advantage of DLL is that it can be traverse backwards while SLL cannot. However, with recursion, you can also traverse SLL in reverse.

  1. Write a recursive method, private void reversePrint(SLLNode temp) inside the given SLL class to print all the elements in the list in reverse order.

  2. Write an auxiliary method, public void reversePrint() to simplify the calling of the recurive method in (a) by calling it with an appropriate initial value for tmp.

  3. Update the given TestIntegerSLL to test your method in (b).