1 / 11

Comp 245 Data Structures

Comp 245 Data Structures. Recursion. What is Recursion?. A problem solving concept which can be used with languages that support the dynamic allocation of memory . In programming, it is the ability for a function to call itself ! The concept has it’s foundation in mathematics.

jeb
Download Presentation

Comp 245 Data Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Comp 245Data Structures Recursion

  2. What is Recursion? • A problem solving concept which can be used with languages that support the dynamic allocation of memory. • In programming, it is the ability for a function to call itself! • The concept has it’s foundation in mathematics.

  3. The Factorial Function • 5! = 5 * 4 *3 * 2 * 1 = 120 • 5! = 5 * 4! = 5 * 4 * 3! = … • Definition 1 if n = 0 n! = if n > 0 n * (n - 1)!

  4. Coding the Factorial FunctionITERATIVELY float Fact (int N) { float product = 1; for (int i = 1; i <= N; i++) product = product * i; return product; }

  5. Coding the Factorial FunctionRECURSIVELY float Fact (int N) { //Anchor Point if ((N == 0) || (N == 1)) return 1; else //Recursive Call – approaches anchor return N * Fact(N – 1); }

  6. Two Requirements for Recursive Code • There must be an anchor point. (Sometimes this is called the base case.) • Each recursive call must approach the anchor point (or base case).

  7. A Walkthru of Recursive Code • Run Time Stack • Winding and Unwinding the stack • Local variables, parameters, return values stored on the stack

  8. Advantage/Disadvantage of Recursion • ADVANTAGE Usually a more concise coding solution, some solutions are more easily implemented using recursion • DISADVANTAGE Less efficient due to overhead involved with function calls.

  9. The Fibonacci Number Sequence • The Italian mathematician Leonardo Fibonacci discovered this sequence which is evident in nature. He discovered the sequence while researching the breeding of rabbits. • The sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … (and so on) • We define the sequence as follows: Fib(0) = 0 Fib(1) = 1 Fib(N) = Fib(N-2) + Fib(N-1) • How would Fib(4) be defined?

  10. Fib(4) – Part I

  11. Coding the Fibonacci FunctionRecursively int Fib (int N) { if ((N==0) || (N==1)) return N; else return Fib(N-1) + Fib(N-2); }

More Related