Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms.

Similar presentations


Presentation on theme: "Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms."— Presentation transcript:

1 Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms

2 Recursive Methods A recursive method is a method that calls itself. Terminating case (Base Case) – Stops the recursive calls

3 Example public class WordPlay{ public static void stackWords(){ String words = IO.readString(); if(word.equals(“.”)) System.out.println(); else stackWords(); System.out.println(word); } public static void main(String args []){ System.out.println(“Enter list of word”); System.out.println(“Final word should be “.”); stackWords(); } Enter hold my hand.

4 Answer. hand my hold ***Note: Computer must go back to finish each method call which is to output word. The first time the method actually terminates, the program returns to complete the most recently invoked previous call.

5 General Form of a Recursive Method Base Case or termination condition that causes the method to end. Usually 1 or 0 or end of file is reached. A nonbase case whose actions move the algorithm toward the base case and termination.

6 Example 2 public void drawLine( int n){ if(n ==0) System.out.println(“That’s all, folks!”); else { for(int i = 1; i <=n; i++) System.out.pprintln(“*”); System.out.println(); drawLine(n-1); } Method call drawLine(3)

7 Answer *** ** * That’s all, folks! ***Note: A method that has no pending statement following the recursive call is an example of tail recursion. Method drawLine is such a case, but not stackWord. Infinite Recursion – Never reaching the base case. StackOverflowError - run out of memory because of infinite recursion.

8 Fibonacci Fibonacci – 1, 1, 2, 3,5,8,13… public static int fib(int n) { if(n == 1 || n == 2) return 1; else return fib(n-1) + fib(n-2); }

9 Fibonacci Fib(5) Fib(4) Fib(3) Fib(2)Fib(1) Fib(2) Fib(3) Fib(2)Fib(1)

10 General Rules for Recursion Avoid recursion for algorithms that involve large local arrays – too many recursive calls cause memory overflow Use recursion when it significantly simplifies code. Avoid recursion for simple iterative methods like factorial, Fibonacci, and the linear search. Recursion is especially useful for – Branching processes like traversing trees or directories. – Divide-and-Conquer algorithms like mergesort and binary search


Download ppt "Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms."

Similar presentations


Ads by Google