Professional Documents
Culture Documents
Recursion
Calling Methods
Can a method call itself?
public void methodB(){
methodB();
System.out.println(B);
}
Recursion
A method that calls itself is called a
recursive method.
A recursive computation solves a problem
by using the solution of the same problem
with simpler values.
int answer = 1;
for(int j=1; j<=4; j++)
{
answer = answer * j;
}
System.out.println(answer);
Computing Factorials
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * ( 2 * (1 * factorial(0)))
= 3 * ( 2 * ( 1 * 1)))
= 3 * ( 2 * 1)
=3*2
=6
Computing Factorials
Computing Factorials
factorial(4) = 4 * factorial(3)
= 4 * (3 * factorial(2)) )
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * ( 2 * (1 *
factorial(0))))
= 4 * (3 * ( 2 * ( 1 * 1)))
= 4 * (3 * ( 2 * 1) )
= 4 * (3 * 2 )
=4*6
= 24
Factorial A Recursive
Solution
public static int factorial(int n)
{
if(n==1)
return 1;
else
return n* factorial(n-1);
}
Type in the code and test factorial(4).
Requirements for
Recursion
1.
2.
Tracing a Recursive
Method
printTriangle(1) prints[]
printTriangle(2) prints[][]
printTriangle(3) prints[][][]
printTriangle(4) prints[][][][]
Example of Recursive
Function
f(0) = 3
f(n) = 2f(n-1) + 3 for n >= 1
Solution of Recursive
Function
f(0) = 3
f(n) = 2f(n-1) + 3 for n >= 1
Practice
Recursion exercise #1
Homework
Barrons Chapter 3 Inheritance &
Polymorphism Question #11-#27