You are on page 1of 26

Introduction to Computing

CS-102
Fall 2018
Instructor: Dr. Jamal Abdul Nasir
Department of Computer Science and Software Engineering
International Islamic University, Islamabad

M o st o f th e m ate rial in th is co u rse is take n fro m D r. Ju stin H sia’s co u rse at W ash in gto n U n ive rsity, afte r w ritte n ap p ro val fro m h im .

CS-102, Fall 2018 Lecture#21&22- Recursion


Recursion
v Recursion is an algorithmic technique where a
function, in order to accomplish a task, calls itself with
some part of the task
§ A function is recursive if the body of the function calls the
function itself

v We’ve seen this before!


§ add(x,y) function from “Beauty in Computer Science”
§ Algorithm for Selection Sort

CS-102, Fall 2018 Lecture#21&22- Recursion 2


Building Blocks of Algorithms
v Sequencing v Selection
§ The application/execution of § Use of conditional to select
each step of an algorithm in which instruction to execute
the order given next
fill(255);
if(mousePressed) {
rectMode(CORNERS);
fill(0,0,255);
rect(-r, -r, 0, r);
}
ellipse(0, -r/2, r, r);

v Iteration v Recursion
§ Repeat part of algorithm a § Algorithm calls itself to help
specified number of times solve the problem on smaller
parts
for(int i=20; i<400; i=i+60) {
line(i,40,i+60,80);
}

CS-102, Fall 2018 Lecture#21&22- Recursion 3


Why Recurse?
v In its most boring form, recursion is simply an
alternative to iteration/looping
§ Anything you can do with iteration, you can do with
recursion (an vice versa)

v However, it is a profoundly powerful way of thinking!


§ Tremendously useful when the problem is self-similar
§ No more powerful than iteration, but often leads to more
concise and “better” code

CS-102, Fall 2018 Lecture#21&22- Recursion 4


Examples of Recursion

CS-102, Fall 2018 Lecture#21&22- Recursion 5


Examples of Recursion

CS-102, Fall 2018 Lecture#21&22- Recursion 6


Peer Instruction Question

v What will happen when we try to run the following


code in Processing? void draw() {
countdown(3);
noLoop();
}
void countdown(int n) {
A. It prints out 3, 2, 1, 0 println(n);
countdown(n-1);
B. It runs forever }
C. Error occurs before execution
D. Error occurs during execution
E. We’re lost…

CS-102, Fall 2018 Lecture#21&22- Recursion 7


Fixing the Countdown
v Without using loops, how would you modify
countdown() to stop at 0?
§ A conditional is needed to stop the infinite loop!

void countdown(int n) { void countdown(int n) {


println(n); if(n<0) {
countdown(n-1); // do nothing
} } else {
println(n);
countdown(n-1);
}
}

CS-102, Fall 2018 Lecture#21&22- Recursion 8


Recursive Solutions
v Base case(s)
§ When the problem is simple enough to be solved directly
§ Needed to prevent infinite recursion

v Recursive case(s)
§ Function calls itself one or more times on “smaller”
problems
• Divide the problem into one or more simpler/smaller parts
• Invoke the function (recursively) on each part
• Combine the solutions of the parts into a solution for the problem

v Depending on the problem, any of these may be trivial or


complex
CS-102, Fall 2018 Lecture#21&22- Recursion 9
Add

int add(int x, int y) {


if(y==0) {
return x;
} else {
return add(x+1,y-1);
}
}

CS-102, Fall 2018 Lecture#21&22- Recursion 10


Add
int add(int x, int y) {
if(y==0) {
return x;
} else {
return add(x+1,y-1);
}
}

§ Divide: y is reduced by 1
§ Invoke: call to add(x+1,y-1)
§ Combine: none

§ Base: y==0 (nothing left to add)

CS-102, Fall 2018 Lecture#21&22- Recursion 11


Add (alternate)
int add(int x, int y) {
if(y==0) {
return x;
} else {
return 1 + add(x,y-1);
}
}

§ Divide: y is reduced by 1
§ Invoke: call to add(x,y-1)
§ Combine: add 1 to result

§ Base: y==0 (nothing left to add)

CS-102, Fall 2018 Lecture#21&22- Recursion 12


Selection Sort
v Algorithm:
§ Find smallest number in an array and move that to the front
§ Repeat this entire procedure, but for the rest of the array

To selection sort this: 7 3 1 8 4

Move 1 to the front: 1 3 7 8 4

Then selection sort this: 1 3 7 8 4

§ Divide: array “size” reduced by 1


§ Invoke: call selection sort on smaller array
§ Combine: smallest number in front of sorted array
§ Base: array of size 1
CS-102, Fall 2018 Lecture#21&22- Recursion 13
Drawing a Recursive Tree

§ Divide: draw smaller tree (fewer levels, shorter branches)


§ Invoke: draw tree as “right branch” and “left branch”
§ Combine: draw branch rotated from end of “trunk”
§ Base: “leaf branches” at end

CS-102, Fall 2018 Lecture#21&22- Recursion 14


Recursive Drawing (video)
v “Recursive Drawing is an exploration of user interface
ideas towards the development of a spatially-oriented
programming environment.”
§ Create drawings without any lines of code!
§ Created by Toby Schachman
§ http://recursivedrawing.com

CS-102, Fall 2018 Lecture#21&22- Recursion 15


Outline
v Example: Tower of Hanoi
v Variable Scope Revisited
v Example: Fibonacci
v Example: Snowflake Fractal

CS-102, Fall 2018 Lecture#21&22- Recursion 16


Tower of Hanoi
v Mathematical puzzle/game
§ Goal is to move entire stack from one peg to any other peg
v Rules:
§ There are only 3 available pegs
§ Can only move
one disk at a
time
§ A disk cannot
sit on top of a
smaller one

CS-102, Fall 2018 Lecture#21&22- Recursion 17


Solving the Tower of Hanoi
v The animation was probably daunting, but the recursive
solution is surprisingly clean
§ Can still be mind-blowingly confusing to understand
§ For illustrative purposes – you’re not responsible for knowing this

v Goal: Move the tower of height 5 from peg 1 to peg 3


§ Let’s assume our solution looks something of the form:
moveTower(int height, int startPeg, int endPeg)

1 2 3
CS-102, Fall 2018 Lecture#21&22- Recursion 18
Solving the Tower of Hanoi
v To reconstruct the tower on peg 3, we first need to
get the largest disk (red) onto peg 3
§ Can’t do this while the other disks are on top
§ Solution: First move the 4 disks on top to peg 2

1 2 3
CS-102, Fall 2018 Lecture#21&22- Recursion 19
Solving the Tower of Hanoi
v To reconstruct the tower on peg 3, we first need to
get the largest disk (red) onto peg 3
§ Can’t do this while the other disks are on top
§ Solution: First move the 4 disks on top to peg 2
• moveTower(4,peg1,peg2); ← just assume it works!

1 2 3
CS-102, Fall 2018 Lecture#21&22- Recursion 20
Solving the Tower of Hanoi
v Now we can move the red disk to peg 3

1 2 3
CS-102, Fall 2018 Lecture#21&22- Recursion 21
Solving the Tower of Hanoi
v Now we can move the red disk to peg 3
§ moveTower(1,peg1,peg3);

v Next Goal: Move the tower of height 4 from peg 2 to


peg 3
§ Solution: First move the 3 disks on top to peg 1, then move
the orange disk to peg 3

1 2 3
CS-102, Fall 2018 Lecture#21&22- Recursion 22
Solving the Tower of Hanoi
v Generalized recursive solution to move tower of
height H from source peg to destination peg:
§ Move tower of height H-1 from source peg to extra peg
§ Move the remaining bottom disk from source peg to
destination peg
§ Move tower of height H-1 from extra peg to destination peg

1 2 3
CS-102, Fall 2018 “Source” “Extra”
Lecture#21&22- Recursion “Destination” 23
Solving the Tower of Hanoi
v Generalized recursive solution to move tower of
height H from source peg to destination peg:
§ moveTower(H-1,peg1,peg2);
§ moveTower(1,peg1,peg3);
§ moveTower(H-1,peg2,peg3);

1 2 3
CS-102, Fall 2018 “Source” “Extra”
Lecture#21&22- Recursion “Destination” 24
Solving the Tower of Hanoi
v What’s the base case?
§ Don’t recurse (but still move disk) when H == 1

1 2 3
CS-102, Fall 2018 “Source” “Extra”
Lecture#21&22- Recursion “Destination” 25
‘Inception’ Analogy (2010 film)
v Each dream is a function call, each “kick” is a function return
§ e.g. the ‘reality’ function calls the ‘Robert Fischer dream’ function
§ Characters are the parameters – they may have the same names, but
are different (clothes?) in every layer

http://images.fastcompany.com/upload/INCEPTION%20infographic%20v3.5.2_dwang.jpg
CS-102, Fall 2018 Lecture#21&22- Recursion 26

You might also like