Fundamentals of Programming

Slides:



Advertisements
Similar presentations
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Advertisements

Recursion. Recursion is a powerful technique for thinking about a process It can be used to simulate a loop, or for many other kinds of applications In.
COSC 2006 Data Structures I Recursion III
Factorial Recursion stack Binary Search Towers of Hanoi
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.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion and Implementation of Functions
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.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
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.
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.
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.
Lecture 7. Solution by Substitution Method T(n) = 2 T(n/2) + n Substitute n/2 into the main equation 2T(n/2) = 2(2(T(n/4)) + n/2) = 4T(n/4) + n And T(n)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion Powerful Tool
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
Recursion CENG 707.
to understand recursion you must understand recursion
Recursion Topic 5.
Topic: Recursion – Part 2
Chapter 15 Recursion.
Introduction to Recursion
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion DRILL: Please take out your notes on Recursion
Abdulmotaleb El Saddik University of Ottawa
Lesson #6 Modular Programming and Functions.
Chapter 4 C Program Control Part I
More on Recursive Recursion vs. Iteration Why Recursion?
Recursion Chapter 12.
Lesson #6 Modular Programming and Functions.
Chapter 15 Recursion.
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
University of Washington Computer Programming I
to understand recursion you must understand recursion
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Lesson #6 Modular Programming and Functions.
Recursion Output Input
Algorithm design and Analysis
Recursion Chapter 11.
Lecture 17 Recursion part 1 Richard Gesick.
Recursion Data Structures.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Coding Concepts (Basics)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 17: Recursion.
Basics of Recursion Programming with Recursion
Memory management Explain how memory is managed in a typical modern computer system (virtual memory, paging and segmentation should be described.
Lesson #6 Modular Programming and Functions.
Recursion Taken from notes by Dr. Neil Moore
Fundaments of Game Design
Chapter 18 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Presentation transcript:

Fundamentals of Programming Recursion

Fundamentals of Programming: Recursion Recursive Functions Whenever we create a subroutine (procedure/function), the subroutine should always exit Otherwise the program gets ‘stuck’ there Usually this is from an infinitely-running iteration Like while(true) However, there are subroutines that can call themselves Called recursive functions Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Recursive Functions A recursive function has the ability to call itself Call: to execute the named procedure/function Recursion is another concept (like iteration and branching) However, there are no keywords needed for implementing a recursive technique We simply make a function call itself within its code block Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Recursive Functions Although recursive functions, by definition, only call themselves We can use them for a large number of purposes For example, we can use recursive techniques as a substitute for iterative techniques We saw this when looking at iteration in a functional language There are times when recursion is more efficient (time and space wise) than using an iterative technique Fundamentals of Programming: Recursion

Recursive Functions As an example of recursion, take the factorial operator Using an iterative technique would mean making a for-loop to run through all the necessary numbers Multiplying them to a total Factorial: The product of all numbers, from 𝑛 to 1 Fundamentals of Programming: Recursion

Recursive Functions However, if we use a recursive function, we can simply return The number we’ve put in Multiplied by the result of the same function (using a decremented argument) Both of these functions calculate the same value with the same input. However, the iterative function makes use of a for-loop, while the recursive function uses recursion. Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Recursive Cases Let’s focus in on this recursive example for a moment Notice the if-statement at the beginning? That if-statement stops this function from running infinitely The factorial of 0 is 1 And negative factorials really aren’t allowed, but we’ll generalise it here as well Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Recursive Cases There are a few terms for something like this That stop a recursive function running indefinitely They can be known as termination conditions, or exit conditions However, we’ll know them as base cases Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Recursive Cases In a recursive function, we have two kinds of cases Possibilities of what we’ll allow First we have base cases These are possible inputs where we know what the result should be In the example of factorial, 0 and 1 return 1 Then we have general cases These are all unknown possibilities where we have to calculate the value The factorial of 3 is calculated from the factorial of 2, and so on Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Recursive Cases This is exactly how most functional programming languages handle things When implementing a function, we first decide what the base case(s) will be We can have multiple base cases Then we move on to the general (catch-all) value to calculate Fundamentals of Programming: Recursion

Illustrating Recursion To show how this function works, let’s try a dry run of the factorial function Using an input of 5 Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 2 factorialRecursive(4) 4 4 * factorialRecursive(3) 3 factorialRecursive(3) 3 * factorialRecursive(2) factorialRecursive(2) 2 * factorialRecursive(1) 2 * 1 factorialRecursive(1) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 2 factorialRecursive(4) 4 4 * factorialRecursive(3) 3 factorialRecursive(3) 3 * factorialRecursive(2) 3 * 2 6 factorialRecursive(2) 2 * factorialRecursive(1) 2 * 1 factorialRecursive(1) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 2 factorialRecursive(4) 4 4 * factorialRecursive(3) 4 * 6 24 3 factorialRecursive(3) 3 * factorialRecursive(2) 3 * 2 6 factorialRecursive(2) 2 * factorialRecursive(1) 2 * 1 factorialRecursive(1) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 5 * 24 120 2 factorialRecursive(4) 4 4 * factorialRecursive(3) 4 * 6 24 3 factorialRecursive(3) 3 * factorialRecursive(2) 3 * 2 6 factorialRecursive(2) 2 * factorialRecursive(1) 2 * 1 factorialRecursive(1) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 2 factorialRecursive(4) 4 4 * factorialRecursive(3) 3 factorialRecursive(3) 3 * factorialRecursive(2) factorialRecursive(2) 2 * factorialRecursive(1) factorialRecursive(1) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 2 factorialRecursive(4) 4 4 * factorialRecursive(3) 3 factorialRecursive(3) 3 * factorialRecursive(2) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 2 factorialRecursive(4) 4 4 * factorialRecursive(3) 3 factorialRecursive(3) 3 * factorialRecursive(2) factorialRecursive(2) 2 * factorialRecursive(1) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) Call Number Function Call 𝒏 Result (1) Result (2) Returned Value 1 factorialRecursive(5) 5 5 * factorialRecursive(4) 2 factorialRecursive(4) 4 4 * factorialRecursive(3) Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Create a recursive function for the sum function Given a single positive integer, add up all numbers from it to 0 Return this sum Once made, test it with the values 5: Result should be 15 10: Result should be 55 Then create a dry run table when running this function with an input of 4 Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion The Program Stack Whenever a program runs a function, it actually saves all the information about local variables This is because, eventually, the program will come back to this point We saw this when looking at the factorial function As the program needs to come back, it will need to keep track of what the values of the local variables in the function we’re going back to Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion The Program Stack It keeps track of this information in something called a stack frame Imagine the stack frame as a little box, which contains enough space for The Stack Frame What is Stored What that is Return Address The address of the next instruction to run when going back to this stack frame Register Contents The values in all the registers in the processor being used in this stack frame Local Variables The values of all local variables created in this stack frame Parameters The values of all the parameters passed into the function for this stack frame Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion The Program Stack Each of these stack frames is stored in the stack A first-in-last-out data-structure Imagine a ‘bucket’ that we put values into A program usually starts at the main function Which will be at the bottom of the stack Any time we call a subroutine, the program stores all the needed values in a stack frame And place it onto the stack The program then continues from this new subroutine When the program completes a subroutine, it pops its stack frame off the stack, and moves back to the previous one Picking up from where it left off The Stack Stack Frame #3 Stack Frame #2 Stack Frame #1 Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion The Program Stack You may have heard of a Stack Overflow error before It’s to do with the stack! Like all data-structures (and places to store data), the stack has a finite amount of space If we call many functions without completing any (like recursive functions), then the stack will fill with stack frames If the stack can’t fit any more stack frames in it, the program crashes Leading to a Stack Overflow error Fundamentals of Programming: Recursion

Clever Use of Recursion Although recursion can be used as a replacement for iteration, recursion’s real worth comes into play when we need to split work amongst many, smaller bits There are lots of algorithms that make use of ‘powerful’ recursion The MergeSort and QuickSort algorithms, for example They split the array to be sorted into smaller arrays first Then knit them together All using recursion Fundamentals of Programming: Recursion

Clever Use of Recursion However, a more playful example is the Towers of Hanoi game This game involves three towers, with decreasing sized disks on the left-most tower Fundamentals of Programming: Recursion

Clever Use of Recursion There is one objective for this game Move all the disks onto the right-most tower That’s it Fundamentals of Programming: Recursion

Clever Use of Recursion However, there are rules Rule #1: we can only move one disk at a time Rule #2: we cannot put a larger disk on top of a smaller disk Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Have a go at the Tower of Hanoi game yourselves! Go to https://www.mathsisfun.com/games/towerofhanoi.html Complete this game for 3 disks, and for 4 disks Fundamentals of Programming: Recursion

Clever Use of Recursion This game has a nice, simple recursive function that can solve it For a tower of any size FUNCTION MoveTower(disk, source, dest, spare) IF disk == 0 move disk from source to dest ELSE MoveTower(disk - 1, source, spare, dest) MoveTower(disk – 1, spare, dest, source) END IF Fundamentals of Programming: Recursion

Clever Use of Recursion The idea of this algorithm is simple When we want to move a disk from one location to another, we have to move all the disks above it first If there are no disks above it (i.e. it is the smallest disk, disk 0) then we can move it straight away FUNCTION MoveTower(disk, source, dest, spare) IF disk == 0 move disk from source to dest ELSE MoveTower(disk - 1, source, spare, dest) MoveTower(disk – 1, spare, dest, source) END IF Fundamentals of Programming: Recursion

Clever Use of Recursion However, if we’re moving a larger disk, then we move the disks above it Because we’re trying to achieve the same result (just with a smaller disk), we can use the same function But changing the destination of all these smaller disks to the spare tower we start with FUNCTION MoveTower(disk, source, dest, spare) IF disk == 0 move disk from source to dest ELSE MoveTower(disk - 1, source, spare, dest) MoveTower(disk – 1, spare, dest, source) END IF Fundamentals of Programming: Recursion

Clever Use of Recursion Once we’ve moved these smaller disks over to the spare tower, we’re free to move the disk we originally wanted to move Of course, this means we’d then need to move all the smaller disks back on top of it FUNCTION MoveTower(disk, source, dest, spare) IF disk == 0 move disk from source to dest ELSE MoveTower(disk - 1, source, spare, dest) MoveTower(disk – 1, spare, dest, source) END IF Fundamentals of Programming: Recursion

Fundamentals of Programming: Recursion Can you implement this algorithm? The source, dest, and spare parameters should be integer arrays Each disk should have a numerical value (from 0 to 𝒏 −𝟏) where 𝑛 is the tower size In the arrays, the 0th index should be the bottom of the tower If a disk is at a potion in the array, put that disk’s numerical value there If there is no disk in a position in the array, put -1 there For example, when making a game with 4 disks, the three arrays should be set up like so: Source: [3, 2, 1, 0] Spare: [-1, -1, -1, -1] Destination: [-1, -1, -1, -1] Fundamentals of Programming: Recursion