2. Recursion
• Recursion is a programming technique in which a
method can call itself to fulfill its purpose
• A procedure that is defined in terms of itself
• In some situations, a recursive definition can be
an appropriate way to express a concept
• Before applying recursion to programming, it is
best to practice thinking recursively
8 - 2
Java Software Structures, 4th Edition, Lewis/Chase
3. Infinite Recursion
• All recursive definitions must have a non-
recursive part
• If they don't, there is no way to terminate the
recursive path
• A definition without a non-recursive part causes
infinite recursion
• This problem is similar to an infinite loop -- with
the definition itself causing the infinite “looping”
• The non-recursive part is called the base case
8 - 3
Java Software Structures, 4th Edition, Lewis/Chase
4. Example
• A simple recursive method that keeps calling
itself forever (no base case)
• A simple recursive method that keeps calling
itself until a base case (count from n to zero)
Java Software Structures, 4th Edition, Lewis/Chase 8 - 4
5. Recursion in Math
• Mathematical formulas are often expressed
recursively
• N!, for any positive integer N, is defined to be the
product of all integers between 1 and N inclusive
• This definition can be expressed recursively:
1! = 1
N! = N * (N-1)!
• A factorial is defined in terms of another factorial
until the base case of 1! is reached
8 - 5
Java Software Structures, 4th Edition, Lewis/Chase
6. A mathematical look
• We are familiar with
f(x) = 3x+5
• How about
f(x) = 3x+5 if x > 10
f(x) = f(x+2) -3 otherwise
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 6
7. Calculate f(5)
f(x) = 3x+5 if x > 10
f(x) = f(x+2) -3 otherwise
• f(5) = f(7)-3
• f(7) = f(9)-3
• f(9) = f(11)-3
• f(11) = 3(11)+5
= 38
But we have not determined what f(5) is yet!
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 7
8. Calculate f(5)
f(x) = 3x+5 if x > 10
f(x) = f(x+2) -3 otherwise
f(5) = f(7)-3 = 29
f(7) = f(9)-3 = 32
f(9) = f(11)-3 = 35
f(11) = 3(11)+5
= 38
Working backwards we see that f(5)=29
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 8
12/31/2022
9. Series of calls
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 9
f(5)
f(7)
f(9)
f(11)
12/31/2022
10. Calculate f(5)
package myjava;
import java.util.*;
public class MyJava {
public static int fun( int x )
{
if( x > 10 )
return (3*x+5); //base step
else
return fun( x +2 ) -3; //recursive step
}
public static void main (String args[]) {
System.out.print("the result of fun(5) = “ + fun( 5 ) );
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 10
12/31/2022
11. Recursive Programming
• A method in Java can invoke itself; if set up that
way, it is called a recursive method
• The code of a recursive method must handle
both the base case and the recursive case
• Each call sets up a new execution environment,
with new parameters and new local variables
• As always, when the method completes, control
returns to the method that invoked it (which may
be another instance of itself)
8 - 11
Java Software Structures, 4th Edition, Lewis/Chase
12. Recursive Programming
• Consider the problem of computing the sum of
all the integers between 1 and N, inclusive
• If N is 5, the sum is
1 + 2 + 3 + 4 + 5
• This problem can be expressed recursively as:
The sum of 1 to N is N plus the sum of 1 to N-1
8 - 12
Java Software Structures, 4th Edition, Lewis/Chase
13. Summation
1+2+3+4+5+…+100
Sum(100) = 1+2+3+…+100
= 1+2+…+ 99 + 100
= sum (99) + 100
sum(n) = sum (n-1) + n
sum(0) = 0
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 13
Recursive step
Base step
12/31/2022
14. Summation Method
package myjava;
import java.util.*;
public class MyJava {
public static int sum( int n )
{
if(n == 0) //base step
return (0);
else //recursive step
return(sum (n-1) +n);
}
public static void main (String args[]) {
Scanner scan=new Scanner(System.in);
System.out.println("enter any number :" );
int x = scan.nextInt();
System.out.println("the summation from 1 to " +x+ " = "+ sum( x ));
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 14
12/31/2022
15. Recursion vs. Iteration
• Just because we can use recursion to solve a
problem, doesn't mean we should
• For instance, we usually would not use recursion
to solve the sum of 1 to N
• The iterative version is easier to understand (in
fact there is a formula that computes it without a
loop at all)
• You must be able to determine when recursion is
the correct technique to use
8 - 15
Java Software Structures, 4th Edition, Lewis/Chase
16. Recursion vs. Iteration
• Every recursive solution has a corresponding
iterative solution
• A recursive solution may simply be less efficient
• Furthermore, recursion has the overhead of
multiple method invocations
• However, for some problems recursive solutions
are often more simple and elegant to express
8 - 16
Java Software Structures, 4th Edition, Lewis/Chase
17. Factorial
4! = 4 * 3 * 2 * 1
n! = n * (n-1) * … * 1
4! = 4 * 3!
n! = n * (n-1)!
factorial(n) = n * factorial(n-1) //recursive step
factorial(1) = 1 //base step
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 17
12/31/2022
18. Method Factorial
package myjava;
import java.util.*;
public class MyJava {
public static int facto( int n )
{
if(n == 1) //base step
return (1);
else //recursive step
return(facto (n-1)*n);
}
public static void main (String args[]) {
Scanner scan=new Scanner(System.in);
System.out.println("enter any number :" );
int x = scan.nextInt();
System.out.println("the summation from 1 to " +x+ " = "+ facto( x ));
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 18
12/31/2022
20. Recursive Implementation of Fibonacci
Numbers
package myjava;
import java.util.*;
public class MyJava {
public static int Fib(int n){
if(n<=1)
return n;
else
return (Fib(n-1)+Fib(n-2));
}
public static void main (String args[]) {
int x =5;
System.out.println("the Fib of " +x + " equal to "+ Fib( x ) );
}
}
PMU,GEIT 2421 Data structures Dr. loayAlzubaidi 20
Fib(5)
Fib(4) Fib(3)
Fib(3) Fib(2)
Fib(2) Fib(1)
Fib(1) Fib(0)
Fib(1) Fib(0)
Fib(1)
Fib(2)
Fib(1) Fib(0)
5
1
0
1 1
2 1
1
0
1
0
1
1
3 2
12/31/2022
21. End of Summer 2130
Java Software Structures, 4th Edition, Lewis/Chase 8 - 21
22. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Tower Of Hanoi
• Goal: Move all disks from A to C
• Rule:
– No bigger disk is on top of smaller disk at any
time
– Move one disk at a time
A B C
4 disks
12/31/2022
22
23. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Tower Of Hanoi
• 1 disk moves from A to C: Simple!
• 2 disks move from A to C
A B C
2 disks
1 2 3
12/31/2022
23
24. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
N disks from A to C?
1. Move n-1 disks from A to B
2. Move disk n from A to C
3. Move n-1 disks from B to C
A B C
disk n
1
n-1 disks
2
3
12/31/2022
24
25. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
4-disk Example
A B C
12/31/2022
25
26. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
4-disk Example
A B C
12/31/2022
26
27. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
4-disk Example
A B C
12/31/2022
27
28. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Recursive Code For Hanoi Tower (Trace of Recursive)
package myjava;
import java.util.*;
public class MyJava {
public static void move(int n, char start, char finish, char buf){
if(n==1) // stop condition: move one disk
System.out.println("Move from " +start + " to "+ finish );
else{
move(n-1,start,buf,finish); // move n-1 from start to buf using
//finish as temporary storage
System.out.println("Move from " +start + " to "+ finish );
move(n-1,buf,finish,start); // move n-1 from buf to finish using
//start as temporary storage
}};
public static void main (String args[]) {
move(3, 'A', 'C', 'B');
}
}
12/31/2022
28
29. PMU,GEIT 2421 Data structures Dr. loayAlzubaidi
Demo Of Hanoi
• A nice animation of Hanoi online:
– https://www.mathsisfun.com/games/
12/31/2022
29
30. Analyzing Recursive Algorithms
• To determine the order of a loop, we determined the
order of the body of the loop multiplied by the number
of loop executions
• Similarly, to determine the order of a recursive method,
we determine the the order of the body of the method
multiplied by the number of times the recursive method
is called
• In our recursive solution to compute the sum of integers
from 1 to N, the method is invoked N times and the
method itself is O(1)
• So the order of the overall solution is O(n)
8 - 30
Java Software Structures, 4th Edition, Lewis/Chase
31. Analyzing Recursive Algorithms
• For the Towers of Hanoi puzzle, the step of
moving one disk is O(1)
• But each call results in calling itself twice more,
so for N > 1, the growth function is
f(n) = 2n – 1
• This is exponential efficiency: O(2n)
• As the number of disks increases, the number of
required moves increases exponentially
8 - 31
Java Software Structures, 4th Edition, Lewis/Chase