Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion CSCE 121 J. Michael Moore.

Similar presentations


Presentation on theme: "Recursion CSCE 121 J. Michael Moore."— Presentation transcript:

1 Recursion CSCE 121 J. Michael Moore

2 Self-Similarity Romanesco broccoli

3 Self-Similarity

4 Fractals Repeated self-similarity can be infinite. Koch Snowflake

5 Landscapes Add randomness to repeated pattern landscapes.

6 Fractal Landscape By The Ostrich - Own work, CC BY 3.0,

7 Mathematically 4!= 4× 4−1 != 4 ×(3!)= 4×(3× 3−1 !)= 4×(3× 2! )= 4×(3× 2× 2−1 ! )= 4×(3× 2× 1! )= 4×(3× 2× 1× 1−1 ! )= 4×(3× 2× 1× 0! )= 4×(3× 2× 1× 1 )= 24 A function defined in terms of itself. Factorial: 𝑛!=𝑛× 𝑛−1 ! Where: 0!=1 Recursive Call. Base case.

8 Recurrence Relationships
Fibonacci Numbers: 𝐹 𝑛 = 𝐹 𝑛−1 + 𝐹 𝑛−2 Where: 𝐹 0 =0 and 𝐹 1 =1 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, … Recursive Calls. Base cases. 𝐹 0 𝐹 1 𝐹 2 𝐹 3 𝐹 4 𝐹 5 𝐹 6 𝐹 7 𝐹 8 𝐹 9 𝐹 10 𝐹 11 𝐹 12 𝐹 13 𝐹 14 1 2 3 5 8 13 21 34 55 ?

9 Computer Science A function that calls itself.
Strongly related to mathematical definition. Think about induction if you have taken a discrete math class. Examples later

10 Factorial Flowchart Self Recursion. Base case. Recursive Call.

11 Indirect/Mutual Recursion.
Contrived Example Indirect/Mutual Recursion.

12 Challenges What if you do not include a base case or get to the base case? Infinite recursion (think of an infinite loop) Each time the recursive call occurs, a new stack frame is created… Eventually, you will run out of memory! Stack Overflow

13 Rules for Good Recursive Function
One or more base cases Always returns without further recursion One or more recursive function calls Must get closer to base case Don‘t forget to use the result of your recursive call!

14 Iteration Recursion is a type of iteration!
Frequently, we use recursion because it looks more like the real problem (e.g. Fibonacci numbers). Every time you call a function there is overhead. Creating stack frame, saving address to return to, etc.

15 Recursion vs. Looping Generally, anything that is written recursively can be converted into a loop. Sometimes, the looping version is more efficient, sometimes not. You will see more useful applications of recursion in 221. Tree and graph traversals, etc. However, we want you to have some exposure now, so you do not have to learn recursion and tackle a harder problem at the same time.


Download ppt "Recursion CSCE 121 J. Michael Moore."

Similar presentations


Ads by Google