Download presentation
Presentation is loading. Please wait.
1
Fundamentals of Programming
Recursion
2
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
3
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
4
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
5
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
6
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
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
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
15
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
16
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
17
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
18
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
19
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
20
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
21
Fundamentals of Programming: Recursion
Have a go at the Tower of Hanoi game yourselves! Go to Complete this game for 3 disks, and for 4 disks Fundamentals of Programming: Recursion
22
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
23
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
24
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
25
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
26
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.