recursion

recursion - Recursion We suppose that you have seen...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Recursion We suppose that you have seen iterative methods in the prerequisite courses. Methods using a loop such as for loops, while loops, or do-while loops are considered to be iterative . Often we can compute the same result using recursion (without using a loop.) In some cases, using recursion enables you to give a natural, straight forward, simple solution to a program that would otherwise be difficult to solve. What is a recursive method? -A method that invokes itself (direct recursion) Example: public void methodA() { methodA(); } Of course the methodA keeps calling itself and this will generate an infinite recursion. Thus we need a stopping condition where it does not call itself. Recursion should have: - recursive case(s) - base case(s) (non-recursive part, stopping condition) If there is no base case, there will be no way to terminate the recursive path. infinite recursion
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Example: For a given positive integer n (i.e., n = 1, 2, 3, 4, …), the method sum is defined by: sum(n) = 1+2+ … + n Using a loop (iterative), this can be computed using a variable that shows the accumulated value for the sum. (here the variable is “result”) public static int sum(int n) { int result = 1; for (int i=2; i<=n; i++) result = result + i; //in this line, “result” on the right hand side is the old value of result, containing the sum from 1 to (i-1) //and the “result on the left hand side if the new value containing the sum from 1 to i.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 9

recursion - Recursion We suppose that you have seen...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online