Recursion Definition Recursion is the computer programming process, whereby a method calls itself.

Slides:



Advertisements
Similar presentations
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
Advertisements

Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Computer Science II Recursion Professor: Evan Korth New York University.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
CS102 Algorithms and Programming II1 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
Review of Recursion. Definition: Recursion - The process of a function calling itself.
Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Unit 7 1 Unit 7: Recursion H Recursion is a fundamental programming technique that can provide an elegant solution to a certain kinds of problems H In.
Department of Computer Engineering Recursive Problem Solving Computer Programming for International Engineers.
Data Structures Using C++ 2E Chapter 6 Recursion.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Data Structures Using C++ 2E Chapter 6 Recursion.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Recursion. Recursive Methods HAVE: 1.A base case or termination condition that causes the method to end 2.A non-base case whose actions move the algorithm.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Recursion. Circular Definition Circular definition Circular definition Dialectic materialism is materialism that is dialectic. Dialectic materialism is.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Tower of Hanoi Tower of Hanoi is a mathematical puzzle invented by a French Mathematician Edouard Lucas in The game starts by having few discs stacked.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Review of Recursion What is a Recursive Method?
Recursion.
Programming and Data Structures
Introduction to Recursion
Introduction to Recursion
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Abdulmotaleb El Saddik University of Ottawa
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
Review of Recursion What is a Recursive Method?
The Hanoi Tower Problem
Section 19.1 Introduction.
Review of Recursion What is a Recursive Method?
Review of Recursion What is a Recursive Method?
Presentation transcript:

Recursion Definition Recursion is the computer programming process, whereby a method calls itself.

Recursion is an important topic with frequent questions on the APCS Examination. The APCS Examination requires that a student can understand and evaluate recursive methods. The APCS Examination does NOT require that students generate free response recursive solutions. APCS Exam Alert

The Grid Problem An image can be represented as a grid of black and white cells. Two cells in an image are part of the same object if each is black and there is a sequence of moves from one cell to the other, where each move is either horizontal or vertical to an adjacent black cell. For example, the diagram on the side represents an image that contains four separate objects, one of them consisting of a single cell. 1

The Grid Problem Complete method alterGrid using the header below, such that all cells in the same object as grid[row][col] are set to white ; otherwise grid is unchanged. grid is a two-dimensional array of boolean elements. An element value of true means a black cell and an element value of false means a white cell. 1 public void alterGrid(boolean grid[ ][ ], int row, int col)

Recursion Requires an Exit The original BASIC programming language makes frequent use of the GOTO control structure. GOTO is very much frowned upon by computer scientists who do not like to see unconditional jumps in a program. 100 REM Program that counts integers starting at K = K = K PRINT K 140 GOTO 120

// Java1701.java // This program demonstrates recursion without an exit. // The recursive calls will continue until the program aborts // with an error message. public class Java1701 { static int k = 0; public static void main(String[ ] args) { count(); } public static void count() { k++; System.out.print(k + " "); count(); }

// Java1702.java // This program demonstrates how to add an exit or base case to control recursive calls public class Java1702 { static int k = 0; public static void main(String[ ] args) { System.out.println("CALLING ITERATIVE COUNT METHOD"); count1(); System.out.println("\n\nCALLING RECURSIVE COUNT METHOD"); count2(); System.out.println("\n\nEXECUTION TERMINATED"); } public static void count1() /***** ITERATIVE COUNT *****/ { for (int k = 1; k <= 100; k++) System.out.print(k + " "); } public static void count2() /***** RECURSIVE COUNT *****/ { k++; System.out.print(k + " "); if (k < 100) count2(); }

Important Recursion Rule All recursive methods must have an exit that stops the recursive process. The special case or condition that stops the recursive calls is called the base case.

// Java1703.java // This program demonstrates the method, which displays // consecutive integers from a to b. public class Java1703 { public static void main(String[ ] args) { System.out.println("CALLING ITERATIVE COUNT METHOD"); count1(10,25); System.out.println("\n\nCALLING RECURSIVE COUNT METHOD"); count2(26,40); System.out.println("\n\nEXECUTION TERMINATED"); } public static void count1(int a, int b) /***** ITERATIVE COUNT *****/ { for (int k = a; k <= b; k++) System.out.print(k + " "); } public static void count2(int a, int b) /***** RECURSIVE COUNT *****/ { if (a <= b) { System.out.print(a + " "); count2(a+1,b); }

// Java1704.java // This program compares the difference between "post-recursive" calls and "pre-recursive" calls. public class Java1704 { public static void main(String[ ] args) { System.out.println("CALLING POST-RECURSIVE COUNT METHOD"); count1(100,200); System.out.println("\n\nCALLING PRE-RECURSIVE COUNT METHOD"); count2(100,200); System.out.println("\n\nEXECUTION TERMINATED"); } public static void count1(int a, int b) /**** POST-RECURSIVE COUNT ****/ { if (a <= b) { System.out.print(a + " "); count1(a+1,b); } public static void count2(int a, int b) /**** PRE-RECURSIVE COUNT ****/ { if (a <= b) { count2(a+1,b); System.out.print(a + " "); }

The Internal Stack & Recursion Java has a special internal data structure, called a stack that is hidden from the programmer. A stack is a data structure that will only access data from one end, usually called the top, in such a manner that it behaves like a LIFO. Data is accessed Last In, First Out. Program execution sequence is handled by something called an Index Pointer. The Index Pointer, or IP for short, contains the next memory address of the line to be executed. NOTE: An IP, which points to a memory address in a computer is in no way related to an Internet Protocol (IP) Address on the internet.

// Java1705.java // This demonstrates how recursion can display output in reverse order. public class Java1705 { public static void main(String[ ] args) { System.out.println("\n\nCALLING PRE-RECURSIVE COUNT METHOD"); count2(100,105); System.out.println("\n\nEXECUTION TERMINATED"); } public static void count2(int a, int b) { if (a <= b) { System.out.println("Interrupting method completion; pushing " + a + " on stack."); count2(a+1,b); System.out.println("Returning to complete method; popping " + a + " from stack."); System.out.println("Displaying popped value " + a); }

Fundamental Recursion Concepts All recursive methods require an or base case that stops the recursive process. The stack controls recursion, since it controls the execution sequence of methods, and stores local method information. Every method call requires the completion of the called method, even if the execution sequence is interrupted by another recursive method call. Incomplete recursive calls result in a LIFO execution sequence.

// Java1706.java This program demonstrates the method. // It also demonstrates recursion with return methods. public class Java1706 { public static void main(String[ ] args) { System.out.println("CALLING ITERATIVE SUM METHOD"); System.out.println(" = " + sum1(6)); System.out.println("\n\nCALLING RECURSIVE SUM METHOD"); System.out.println(" = " + sum2(100)); System.out.println("\n\nEXECUTION TERMINATED"); } public static int sum1(int n) /***** ITERATIVE SUM *****/ { int sum = 0; for (int k = 1; k <= n; k++) sum += k; return sum; } public static int sum2(int n) /***** RECURSIVE SUM *****/ { if (n == 0) return 0; else return n + sum2(n-1); }

Stepping Through the Recursive Process with sum2(4) CALL #nMethod sum2 returns Sum2(3) 3 + Sum2(2) 2 + Sum2(1) 1 + Sum2(0) 0 sum2(4) = = 10

Sum Method Backwards From Base Case to Start

// Java1707.java // This program demonstrates the method. public class Java1707 { public static void main(String[ ] args) { System.out.println("CALLING ITERATIVE FACTORIAL METHOD"); System.out.println("6 Factorial = " + fact1(6)); System.out.println("\n\nCALLING RECURSIVE FACTORIAL METHOD"); System.out.println("7 Factorial = " + fact2(7)); System.out.println("\n\nEXECUTION TERMINATED"); } public static int fact1(int n) /***** ITERATIVE FACT *****/ { int temp = 1; for (int k = n; k > 0; k--) temp *= k; return temp; } public static int fact2(int n) /***** RECURSIVE FACT *****/ { if (n == 0) return 1; else return n * fact2(n-1); } Doesn’t this look like the mathematical definition of factorial?

Factorial Method Backwards From Base Case to Start

// Java1708.java This program demonstrates the method. public class Java1708 { public static void main(String[ ] args) { System.out.println("CALLING ITERATIVE GCF METHOD"); System.out.println("GCF of 120 and 108 is " + gcf1(120,108)); System.out.println("\n\nCALLING RECURSIVE GCF METHOD"); System.out.println("GCF of 360 and 200 is " + gcf2(360,200)); System.out.println("\n\nEXECUTION TERMINATED"); } public static int gcf1(int n1, int n2) /***** ITERATIVE GCF *****/ { int temp = 0;int rem = 0; do { rem = n1 % n2; if (rem == 0)temp = n2; else { n1 = n2; n2 = rem; } while (rem != 0); return temp; }

Stepping Through the Recursive Process with gcf2(360,200) public static int gcf2(int n1, int n2) { int rem = n1 % n2; if (rem == 0) return n2; else return gcf2(n2,rem); } CALL#n1n2remMethod gcf2 returns gcf2(200,160) gcf2(160,40) 40 gcf2(360,200) = 40

Fibonacci, a Recursive No-No The Fibonacci Sequence is a sequence of numbers, starting with two ones, which is created by taking the sum of the two previous numbers.

// Java1709.java // This program demonstrates the method. Note that this style of recursion becomes // unacceptibly slow when the requested Fibonacci number becomes larger. import java.util.*; public class Java1709 { public static void main(String[ ] args) { Scanner input = new Scanner(System.in); System.out.print("Enter requested Fibonacci number ===>> "); int number = input.nextInt(); System.out.println("\n\nCALLING ITERATIVE FIBO METHOD"); System.out.println("Fibonacci(" + number + ") is " + fibo1(number)); System.out.println("\n\nCALLING RECURSIVE FIBO METHOD"); System.out.println("Fibonacci(" + number + ") is " + fibo2(number)); System.out.println("\n\nEXECUTION TERMINATED"); }

/***** ITERATIVE FIBO *****/ public static int fibo1(int n) { int n1 = 1; int n2 = 1; int n3 = 1; if (n == 1 || n == 2) return 1; else { for (int k = 3; k <= n; k++) { n3 = n1 + n2; n1 = n2; n2 = n3; } return n3; }

/***** RECURSIVE FIBO *****/ public static int fibo2(int n) { if (n == 1 || n == 2) return 1; else return fibo2(n-1) + fibo2(n-2); } The problem with the recursive solution can be seen when you view how quickly the time to compute the Fibo numbers increases: Fibo#TimeFibo#Time 413 seconds511 hour 426 seconds584½ days 4312 seconds611 month 4424 seconds811,000,000 months

Tracing the Fibo Method

Fibonacci Problem Explained

Recursion Warning Avoid recursive methods that have a single program statement with multiple recursive calls, like the Fibonacci Sequence: return fibo(n-1) + fibo(n-2);

APCS Exam Alert Evaluating recursive method, like the examples that follow will be required for both the multiple choice part and the free response part of the examination. Few students are comfortable with this type of problem at the first introduction. Most students achieve excellent evaluation skills with repeated practice.

Multiple Recursive Calls and The Tower of Hanoi Towers of Hanoi at the Start of the 5-Disk Problem Peg APeg BPeg C

Multiple Recursive Calls and The Tower of Hanoi Peg APeg BPeg C Towers of Hanoi at the End of the 5-Disk Problem

The Trivial One-Disk Problem Let us look at a variety of problems, starting with the simplest possible situation. Suppose that you only need to move one disk from peg A to peg C. Would that be any kind of problem? 1 Peg APeg BPeg C

The Trivial One-Disk Problem How do we solve the 1-Disk problem? In exactly one step that be described with the single statement: Move Disk1 from Peg A to Peg C 1 Peg APeg BPeg C

The Easy Two-Disk Problem Start Peg APeg BPeg C 2 1

The Easy Two-Disk Problem Step 1 Peg APeg BPeg C 2 1

The Easy Two-Disk Problem Step 2 Peg APeg BPeg C 2 1

The Easy Two-Disk Problem Step 3 - Finished Peg APeg BPeg C 2 1

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Start

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 1

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 2

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 3

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 4

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 5

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 6

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 7

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 8

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 9

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 10

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 11

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 12

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 13

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 14

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 15

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 16

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 17

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 18

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 19

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 20

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 21

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 22

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 23

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 24

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 25

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 26

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 27

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 28

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 29

The Tower of Hanoi 5 Disk Demo Peg APeg BPeg C Step 30

Peg APeg BPeg C The Tower of Hanoi 5 Disk Demo Step 31 - Finished

Tower of Hanoi Formula There is a pattern in the number of minimum moves to solve a given Tower of Hanoi problem. With n the number of disks to be moved, the formula below computes the number or required moves. 2 n – 1

// Java1710.java This program solves the "Tower of Hanoi" puzzle. import java.util.*; public class Java1710 { public static void main(String[ ] args) { Scanner input = new Scanner(System.in); System.out.print("\nHow many disks are in the tower ===>> "); int disks = input.nextInt(); solveHanoi('A','B','C',disks); System.out.println("\n\nEXECUTION TERMINATED"); } public static void solveHanoi(char s, char t, char d, int n) // s - source peg t - temporary peg d - destination peg n - number of disks { if (n != 0) { solveHanoi(s,d,t,n-1); System.out.println("Move Disk "+n+" From Peg "+ s + " to Peg " + d); solveHanoi(t,s,d,n-1); } YES! That’s it!

Tower of Hanoi General Solution Move n-1 disks from Source Peg to Auxiliary Peg Move the nth disk from Source Peg to Destination Peg Move n-1 disks from Auxiliary Peg to Destination Peg

Tower of Hanoi Formula Towers of Hanoi at Start of N-Disk Problem N N - 1 N Peg APeg BPeg C

Tower of Hanoi Formula Move N-1 Disks from Peg A to Peg B N N - 1 N Peg APeg BPeg C

Tower of Hanoi Formula Move Nth Disk from Peg A to Peg C N N - 1 N Peg APeg BPeg C

Tower of Hanoi Formula Move N-1 Disks from Peg B to Peg C N N - 1 N Peg APeg BPeg C

Why Recursion? Recursion is preferred over iteration when it is easier to write program code recursively.

The Grid Problem Revisited Complete method alterGrid using the header below, such that all cells in the same object as grid[row][col] are set to white ; otherwise grid is unchanged. grid is a two-dimensional array of boolean elements. An element value of true means a black cell and an element value of false means a white cell. 1 public void alterGrid(boolean grid[ ][ ], int row, int col)

// Java1711.java // Recursive solution to the black/white "Grid" problem public static void alter(boolean grid[][], int r, int c) { if ((r >= 1) && (r <= 10) && (c >= 1) && (c <= 10)) if (grid[r][c]) { grid[r][c] = false; alter(grid,r-1,c); alter(grid,r+1,c); alter(grid,r,c-1); alter(grid,r,c+1); }