Chapter 17 Recursion.

Slides:



Advertisements
Similar presentations
Ch. 8 Functions.
Advertisements

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 17 Recursion. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Mathematical Definition: RunningSum(1)
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
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 CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Chapter 19 Recursion.
Recursion Gordon College CPS212
Overview C programming Environment C Global Variables C Local Variables Memory Map for a C Function C Activation Records Example Compilation.
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.
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
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.
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.
Runtime Environments Compiler Construction Chapter 7.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Recursion.  A recursive function contains a call to itself Example: the factorial n!=n*(n-1)! for n>1 n!=1 for n=1 int factorial (int n) { if (n == 0)
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Data Structures and Algorithms Stacks. Stacks are a special form of collection with LIFO semantics Two methods int push( Stack s, void *item ); - add.
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.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
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:
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
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 Chapter 8 Recursion. 2 Recursive Function Call a recursion function is a function that either directly or indirectly makes a call to itself. but we.
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.
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.
Recursion CENG 707.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion CENG 707.
to understand recursion you must understand recursion
Data Structures with Java © Rick Mercer
RECURSION.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion DRILL: Please take out your notes on Recursion
Data Structures and Algorithms
Chapter 17 Recursion.
Chapter 12 Variables and Operators
Programming Fundamentals Lecture #7 Functions
Chapter 14 Functions.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 14 Functions.
Chapter 17 Recursion.
Recursion Chapter 11.
Chapter 18-3 Recursion Dale/Weems.
Chapter 14 Functions.
Chapter 17 Recursion.
Module 1-10: Recursion.
Java Programming: Chapter 9: Recursion Second Edition
When a function is called...
Yan Shi CS/SE 2630 Lecture Notes
Chapter 18 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Runtime Environments What is in the memory?.
Where is all the knowledge we lost with information? T. S. Eliot
Recursive Algorithms 1 Building a Ruler: drawRuler()
Chapter 14 Functions.
Midterm 1 Review CS270 - Spring Semester 2019.
Chapter 14 Functions.
Implementing Functions: Overview
Presentation transcript:

Chapter 17 Recursion

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 ( ) 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); }

Executing RunningSum res = RunningSum(4); return 4 + RunningSum(3); return value = 10 return 4 + RunningSum(3); RunningSum(3) return value = 6 return 3 + RunningSum(2); RunningSum(2) return value = 3 return 2 + RunningSum(1); RunningSum(1) return value = 1 return 1;

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.

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); }

Detailed Example: Fibonacci Numbers Mathematical Definition: In other words, the n-th Fibonacci number is the sum of the previous two Fibonacci numbers.

Fibonacci: C Code int Fibonacci(int n) { if ((n == 0) || (n == 1)) return 1; else return Fibonacci(n-1) + Fibonacci(n-2); }

main calls Fibonacci(3) Activation Records Whenever a function is invoked, a new activation record is pushed onto the stack. Stack grows from higher to lower addresses. The stack pointer SP points to the last filled location. In LC3, R6 serves as the SP. main calls Fibonacci(3) R6 Fib(3) main

Fibonacci: LC-3 Code Activation Record temp dynamic link return address return value n local bookkeeping Compiler generates temporary variable to hold result of first Fibonacci call. arg

Activation Records Whenever Fibonacci is invoked, a new activation record is pushed onto the stack. main calls Fibonacci(3) Fibonacci(3) calls Fibonacci(2) Fibonacci(2) calls Fibonacci(1) R6 Fib(1) R6 Fib(2) Fib(2) R6 Fib(3) Fib(3) Fib(3) main main main

Activation Records (cont.) Fibonacci(1) returns, Fibonacci(2) calls Fibonacci(0) Fibonacci(2) returns, Fibonacci(3) calls Fibonacci(1) Fibonacci(3) returns R6 Fib(0) R6 Fib(2) Fib(1) Fib(3) Fib(3) R6 main main main

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?

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'); } }

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')

LC-2 Code Skip for now

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

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

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