This preview shows pages 1–3. Sign up to view the full content.
Recursion
We suppose that you have seen iterative methods in the prerequisite courses. Methods using a loop such as for loops, while loops,
or dowhile 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) (nonrecursive part, stopping condition)
If there is no base case, there will be no way to terminate the recursive path.
→
infinite recursion
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentExample:
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 (i1)
//and the “result on the left hand side if the new value containing the sum from 1 to i.
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '09
 Balasooriya/Kouvetakis
 Recursion

Click to edit the document details