200 likes | 444 Views
Recursion Sir Joseph Lindo University of the Cordilleras. Recursion. R ecursion. Definition. Definition. It is a programming technique in which a call to a method appears in that method’s body
E N D
Recursion Sir Joseph Lindo University of the Cordilleras
Recursion Recursion Definition Definition It is a programming technique in which a call to a method appears in that method’s body Once you understand recursive methods, they are often simpler to write than their iterative equivalents No Iteration Application Activity
Recursion Recursion vs Iteration Activity Definition No Iteration No Iteration Problem: Collect $1,000.00 for charity Assumption: Everyone is willing to donate a penny Application Activity
Recursion Recursion vs Iteration Activity Definition No Iteration No Iteration • Iterative Solution • Visit 100,000 people, asking each for a penny • Recursive Solution • If you are asked to collect a penny, give a penny to the person who asked you for it Application Activity
Recursion Basic Applications Activity Definition No Iteration Application Application Activity
Recursion Group Activity Activity Definition Create the flow chart of a Fibonacci Sequence with the following conditions: 1 is always the start Accept the number of series to be printed from the user. No Iteration Application Activity Activity
Recursion Assignment Activity Definition Create the flow chart of a simple Factorial in a one whole yellow paper, wherein the number must come from the user and there is no negative number. No Iteration Application Activity Activity
Recursion --end-- Sir Joseph Lindo University of the Cordilleras
Factorial Definition jo • A factorial is defined as follows: • n! = n * (n-1) * (n-2) …. * 1; • For example: • 1! = 1 (Base Case) • 2! = 2 * 1 = 2 • 3! = 3 * 2 * 1 = 6 • 4! = 4 * 3 * 2 * 1 = 24 • 5! = 5 * 4 * 3 * 2 * 1 = 120 If you will study the examples you will start to see a pattern
Factorial Definition jo Example using the pattern 10 = 10 * 9! 5! = 5 * 4! 4! = 4 * 3!
Factorial Code jo Iterative approach: intfactorial (int n) { int answer = 1; for (inti=1; i<=n; i++) answer *= i; return answer; }
Factorial Code jo Recursive approach: int factorial (int n) { if (n == 0) return 1; else return n * factorial(n-1); }
Fibonacci Sequence Definition jo The sequence begins with one Each subsequent number is the sum of the two preceding numbers Fib(n) = Fib(n-1) + Fib(n-2) 1, 1, 2, 3, 5, 8, 13 . . .
Fibonacci Sequence Applications jo Many aspects of nature are grouped in bunches equaling Fibonacci numbers.
Fibonacci Sequence Applications jo Music involves several applications of Fibonacci numbers. A full octave is composed of 13 total musical tones, 8 of which make up the actual musical octave.
Fibonacci Sequence Applications jo Paintings
Fibonacci Sequence Applications jo Human Body The lengths of bones in a hand are Fibonacci numbers.
Fibonacci Sequence Diagram jo
Fibonacci Sequence Diagram jo
Fibonacci Sequence Diagram jo