Chapter 5: Enhancing Classes

Download Report

Transcript Chapter 5: Enhancing Classes

Recursion
 Recursion is a programming technique in which a
method can call itself to solve a problem
 It is really useful for Artificial Intelligence (like a
chess game), where it will make a move considering
how the game would play out if it made that move.
 Problems were its solution is defined by itself. Think
of 6! It is made up of 6 * 5! And so on.
1
Infinite Recursion
 All recursive definitions must have a non-recursive
part
 If they don't, there is no way to terminate the
recursive path. Like for 6!, eventually we get to
6*5*4*3*2*1 at 1, we don’t have it continue *0*-1… WE
STOP.
 A definition without a non-recursive part causes
infinite recursion
2
Recursive Definitions
 This definition can be expressed recursively as:
1!
N!
=
=
1
N * (N-1)!
 The concept of the factorial is defined in terms of
another factorial until the base case of 1! is reached
3
Recursive Definitions
120
5!
24
5 * 4!
4 * 3!
6
3 * 2!
2 * 1!
2
1
4
Recursive Programming
 Consider the problem of computing the sum of all the
numbers between 1 and any positive integer N,
inclusive
 This problem can be expressed recursively as:
N
N-1
=
N
i=1
=
+
N-2
=
i=1
N + (N-1) +
i=1
etc.
5
Recursive Programming
public int sum (int num)
{
int result;
if (num == 1)
result = 1;
else
result = num + sum (num - 1);
return result;
}
6
Recursive Programming
result = 6
main
sum(3)
sum
result = 3
sum(2)
sum
result = 1
sum(1)
sum
7