80 likes | 165 Views
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 :
E N D
CSE 1341 - HonorsPrinciples 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 : • Iterative method of problem solving • Used a disciplined sequence of method calls and control structures to get the job done
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”
Recursion Example Factorial …. 1! = 1 n! = n * (n – 1)!, n > 1 Figure 15.2
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
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) = ???
Fibonacci public static long fibonacci(long num) { if (num == 0 || num == 1) return num; else return fibonacci(num – 1) + fibonacci(num – 2); }