CH 5.2 - Recursion
CH 5.2 - Recursion
Data Structures
A base case: the part that is processed without recursion (termination case).
A general case: the part that is reduced to one, or more, smaller cases. Each time a
recursive call is made, it comes closer to the base case.
Begin by asking yourself “How can this problem be divided into parts?”.
Be sure to keep your answer simple but applicable in the general case.
Combine the stopping rule and the general step, using an if statement to select between
them.
You should now be able to write the main program and a recursive function that will
describe how to subdivide the problem until the stopping rule applies.
Check termination
Verify that the recursion will always terminate. Start with a general situation and check
that, in a finite number of steps, the stopping rule will be satisfied and the recursion will
terminate.
Faculty of Information Technology - Computer Science Department 8
How Function Calls Work
When a function is called, it must have a storage area which is used to save all needed
data for this call as calling parameters, local variables, return value, …etc.
When the function returns, the storage area is released.
In the Figure below, we have:
The function main(…) calls the function r(…).
The function r(…) calls the function s(…), which calls the function t(…)
Each time a recursive function is called, a new copy of the function runs, with new
instances of parameters and local variables being created.
As each copy finishes executing, it returns to the copy of the function that called it.
When the initial copy finishes executing, it returns to the part of the program that
made the initial call to the function.
Example 1 Output
Output
Try to modify this section to become: 5
RecFun(n-1); 4
System.out.println(n + " "); 3
what will the output be?? 2
1
Stop!
Faculty of Information Technology - Computer Science Department 14
Solving Recursively Defined Problems
The natural definition of some problems leads to a recursive solution.
Example 1: Factorial Problem
The factorial of a nonnegative integer n is the product of all positive integers less or
equal to n.
The factorial of n is denoted by n!
The factorial of 0 is 1.
0!=1
n ! = n × (n-1) × … × 2 × 1 if n > 0
Factorial of n can be expressed in terms of the factorial of n-1
0!=1
n ! = n x (n-1) ! Faculty of Information Technology - Computer Science Department 15
Solving Recursively Defined Problems
• n ! = n × (n-1) × … × 2 × 1 if n > 0
5!=5 × 4 × 3 × 2 × 1=120
• n ! = n x (n-1) !
– 5!=5 × 4!
– 5!=5 ×4 × 3!
– 5!=5 ×4 × 3 ×2!
– 5!=5 ×4 × 3 ×2 ×1!
– 5!=5 ×4 × 3 ×2 ×1 ×0!
– 5!=5 ×4 × 3 ×2 ×1 ×1
Recursion is usually used with linked list processing to iterate (traverse) the linked
list backwards.
For example, if we want to reverse print the content of a linked list we can achieve
that easily using recursion.
Recursion