Chapter 17 Recursion. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 17-2 Mathematical Definition: RunningSum(1)

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Advertisements

Starting Out with Java: From Control Structures through Objects
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
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 Gordon College CPS212
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Function Smaller, simpler, subcomponent.
CMPE13Cyrus Bazeghi Chapter 14 Functions in C. CMPE13 2 Functions Smaller, simpler, subcomponents of programs Provide abstraction –hide low-level details.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementation:
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Department of Computer Science Data Structures Using C++ 2E Chapter 6: Recursion Learn about recursive Definitions Algorithms Functions Explore the base.
Functions & Activation Records Recursion
Recursion, C and Beyond "… but it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong!" --Linus.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CMPE13 Cyrus Bazeghi Chapter 17 Recursion. CMPE13 What is Recursion? A recursive function is one that solves its task by calling itself on smaller pieces.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
CSE 1342 Programming Concepts Recursion. Overview of Recursion nRecursion is present when a function is defined in terms of itself. nThe factorial of.
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.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
Introduction to Computing Systems from bits & gates to C & beyond Chapter 10 The Stack Stack data structure Activation records and function invocation.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Functions-Recall 1. 2 Parameter passing & return void main() { int x=10, y=5; printf (“M1: x = %d, y = %d\n”, x, y); interchange (x, y); printf (“M2:
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9-2 JSR Instruction Jumps to a location (like.
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Declarations (aka prototype) int.
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.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
1 ADT Implementation: Recursion, Algorithm Analysis Chapter 10.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Recursion Chapter 2 Objectives Upon completion you will be able to:
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Recursion,
1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion.
Chapter 14 Functions.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Chapter 15 Recursive Algorithms
Chapter 17 Recursion.
Chapter 12 Variables and Operators
Chapter 14 Functions.
Chapter 14 Functions.
Chapter 17 Recursion.
Recursion Data Structures.
Chapter 14 Functions.
Chapter 17 Recursion.
CSC 143 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 14 Functions.
Chapter 17 Recursion.
Chapter 14 Functions.
Implementing Functions: Overview
Presentation transcript:

Chapter 17 Recursion

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Mathematical Definition: RunningSum(1) = 1 RunningSum(n) = n + RunningSum(n-1) Recursive Function: int RunningSum(int n) { if (n == 1) return 1; else return n + RunningSum(n-1); } What is Recursion? A recursive function is one that solves its task by calling itself on smaller pieces of data. Similar to recurrence function in mathematics. Like iteration -- can be used interchangeably; sometimes recursion results in a simpler solution. Example: Running sum ( )

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Executing RunningSum RunningSum(4) RunningSum(3) RunningSum(2) RunningSum(1) return value = 1 return value = 3 return value = 6 return value = 10 return 1; return 2 + RunningSum(1); return 3 + RunningSum(2); return 4 + RunningSum(3); res = RunningSum(4);

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display High-Level Example: Binary Search Given a sorted set of exams, in alphabetical order, find the exam for a particular student. 1. Look at the exam halfway through the pile. 2. If it matches the name, we're done; if it does not match, then... 3a. If the name is greater (alphabetically), then search the upper half of the stack. 3b. If the name is less than the halfway point, then search the lower half of the stack.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Binary Search: Pseudocode Pseudocode is a way to describe algorithms without completely coding them in C. FindExam(studentName, start, end) { halfwayPoint = (end + start)/2; if (end < start) ExamNotFound(); /* exam not in stack */ else if (studentName == NameOfExam(halfwayPoint)) ExamFound(halfwayPoint); /* found exam! */ else if (studentName < NameOfExam(halfwayPoint)) /* search lower half */ FindExam(studentName, start, halfwayPoint - 1); else /* search upper half */ FindExam(studentName, halfwayPoint + 1, end); }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display High-Level Example: Towers of Hanoi Task: Move all disks from current post to another post. Rules: (1) Can only move one disk at a time. (2) A larger disk can never be placed on top of a smaller disk. (3) May use third post for temporary storage. Post 1Post 2Post 3

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Task Decomposition Suppose disks start on Post 1, and target is Post Move top n-1 disks to Post Move largest disk to Post Move n-1 disks from Post 2 to Post

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Task Decomposition (cont.) Task 1 is really the same problem, with fewer disks and a different target post. "Move n-1 disks from Post 1 to Post 2." And Task 3 is also the same problem, with fewer disks and different starting and target posts. "Move n-1 disks from Post 2 to Post 3." So this is a recursive algorithm. The terminal case is moving the smallest disk -- can move directly without using third post. Number disks from 1 (smallest) to n (largest).

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Towers of Hanoi: Pseudocode MoveDisk(diskNumber, startPost, endPost, midPost) { if (diskNumber > 1) { /* Move top n-1 disks to mid post */ MoveDisk(diskNumber-1, startPost, midPost, endPost); printf("Move disk number %d from %d to %d.\n", diskNumber, startPost, endPost); /* Move n-1 disks from mid post to end post */ MoveDisk(diskNumber-1, midPost, endPost, startPost); } else printf("Move disk number 1 from %d to %d.\n", startPost, endPost); }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Detailed Example: Fibonacci Numbers Mathematical Definition: In other words, the n-th Fibonacci number is the sum of the previous two Fibonacci numbers.

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Fibonacci: C Code int Fibonacci(int n) { if ((n == 0) || (n == 1)) return 1; else return Fibonacci(n-1) + Fibonacci(n-2); }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Activation Records Whenever Fibonacci is invoked, a new activation record is pushed onto the stack. Fib(1) R6 Fib(2) Fib(3) main main calls Fibonacci(3) Fibonacci(3) calls Fibonacci(2) Fibonacci(2) calls Fibonacci(1) R6 Fib(3) main R6 Fib(2) Fib(3) main

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Activation Records (cont.) Fibonacci(1) returns, Fibonacci(2) calls Fibonacci(0) Fibonacci(2) returns, Fibonacci(3) calls Fibonacci(1) Fibonacci(3) returns R6 main R6 Fib(1) Fib(3) main Fib(0) R6 Fib(2) Fib(3) main

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Tracing the Function Calls If we are debugging this program, we might want to trace all the calls of Fibonacci. Note: A trace will also contain the arguments passed into the function. For Fibonacci(3), a trace looks like: Fibonacci(3) Fibonacci(2) Fibonacci(1) Fibonacci(0) Fibonacci(1) What would trace of Fibonacci(4) look like?

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Fibonacci: LC-3 Code Activation Record temp dynamic link return address return value n bookkeeping arg Compiler generates temporary variable to hold result of first Fibonacci call. local

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display LC-2 Code (part 1 of 3) Fibonacci ADD R6, R6, #-2 ; skip ret val, push ret addr STR R7, R6, #0 ADD R6, R6, #-1 ; push dynamic link STR R5, R6, #0 ADD R5, R6, #-1 ; set frame pointer ADD R6, R6, #-2 ; space for locals and temps LDR R0, R5, #4 ; load n BRz FIB_BASE ; check for terminal cases ADD R0, R0, #-1 BRz FIB_BASE

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display LC-3 Code (part 2 of 3) LDR R0, R5, #4 ; read parameter n ADD R0, R0, #-1 ; calculate n-1 ADD R6, R6, #-1 ; push n-1 STR R0, R6, #0 JSR Fibonacci ; call self LDR R0, R6, #0 ; pop return value ADD R6, R6, #1 STR R0, R5, #-1 ; store in temp LDR R0, R5, #4 ; read parameter n ADD R0, R0, #-2 ; calculate n-2 ADD R6, R6, #-1 ; push n-2 STR R0, R6, #0 JSR Fibonacci ; call self

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display LC-3 Code (part 3 of 3) LDR R0, R6, #0 ; pop return value ADD R6, R6, #1 LDR R1, R5, #-1 ; read temp ADD R0, R0, R1 ; Fibonacci(n-1) + Fibonacci(n-2) BRnzp FIB_END ; all done FIB_BASE AND R0, R0, #0 ; base case – return 1 ADD R0, R0, #1 FIB_END STR R0, R5, #3 ; write return value (R0) ADD R6, R5, #1 ; pop local variables LDR R5, R6, #0 ; pop dynamic link ADD R6, R6, #1 LDR R7, R6, #0 ; pop return address ADD R6, R6, #1 RET

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display A Final C Example: Printing an Integer Recursively converts an unsigned integer as a string of ASCII characters. If integer <10, convert to char and print. Else, call self on first (n-1) digits and then print last digit. void IntToAscii(int num) { int prefix, currDigit; if (num < 10) putchar(num + '0'); /* prints single char */ else { prefix = num / 10; /* shift right one digit */ IntToAscii(prefix); /* print shifted num */ /* then print shifted digit */ currDigit = num % 10; putchar(currDigit + '0'); } }

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Trace of IntToAscii Calling IntToAscii with parameter 12345: IntToAscii(12345) IntToAscii(1234) IntToAscii(123) IntToAscii(12) IntToAscii(1) putchar('1') putchar('2') putchar('3') putchar('4') putchar('5')