1 / 8

CSE 1341 - Honors Principles of Computer Science I

CSE 1341 - Honors Principles of Computer Science I. Spring 2008 Mark Fontenot mfonten@engr.smu.edu. Note Set 18. Note Set 18 Overview. Recursion Base case/recursive case Factorial Fibonacci. Recursion a method of problem solving pervasive in computational sciences Before :

love
Télécharger la présentation

CSE 1341 - Honors Principles of Computer Science I

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. CSE 1341 - HonorsPrinciples of Computer Science I Spring 2008 Mark Fontenot mfonten@engr.smu.edu Note Set 18

  2. Note Set 18 Overview • Recursion • Base case/recursive case • Factorial • Fibonacci

  3. Recursion • a method of problem solving • pervasive in computational sciences • Before : • Iterative method of problem solving • Used a disciplined sequence of method calls and control structures to get the job done

  4. Recursive Method Method calls a fresh copy of itself with this similar problem This is the recursive case. A recursive method is one that calls itself in order to solve a problem Based on the idea of divide-and-conquer problem solving technique Recursive method is only actually capable of solving the simplest case of the problem called the base case If method is called with base case, result returnedelse it is called with more complex problem method divides prob into 2 pieces One piece it knows how to do, The other it does not – but this piece must be similar to original problem, just “smaller”

  5. Recursion Example Factorial …. 1! = 1 n! = n * (n – 1)!, n > 1 Figure 15.2

  6. Recursion Example public static long factorial(long num) { if (num <= 1) return 1; else return num * factorial(num – 1); } Leaving out base case or having invalid base case can lead to infinite recursion Base Case Recursive Case

  7. Fibonacci Sequence Mathematical Definition: f(0) = 0; f(1) = 1; f(n) = f(n-1) + f(n-2), n > 1 f(3) = f(2) + f(1) = ???

  8. Fibonacci public static long fibonacci(long num) { if (num == 0 || num == 1) return num; else return fibonacci(num – 1) + fibonacci(num – 2); }

More Related