Recursion
Recursion
Chapter 6
Recursion
Print *
Fun2(2)
Print 2
Call fun3(1) ...
Print &
Fun3(1)
Print 1
Print $
Fun(2)
Print 2
Call fun(1) ...
Print a= 2
Fun(1)
Print 1
Call fun(0) ...
Print a= 1
Fun(0)
Edited by Malak Abdullah
Jordan University of Science and Technology Print a= 0
5!= 5 * ( 4 *( 3* (2 * (1))))
Fact1(5)
void main( )
{ 5 * Fact1(4)
cout<< fact (5)<<endl;
4 * Fact1(3)
}
3 * Fact1(2)
2 * Fact1(1)
1 * Fact1(0)
Fact1(5)
120
void main( )
{ 5 * Fact1(4)
24
cout<< fact (5)<<endl;
4 * Fact1(3)
6
}
3 * 2
Fact1(2)
2 * Fact1(1)
1
1 * Fact1(0)
1
Reverse(135)
Print 135 % 10 →5
Call reverse(13)
Reverse(13)
Print 13 % 10 →3
Call reverse(1)
Reverse(1)
Print 1
Fact1(5)
5 Fact1(4)
4 Fact1(3)
3 Fact1(2)
2 Fact1(1)
1 Fact1(0)
Fact2(5)
5 Fact2(4)
4 Fact2(3)
3 Fact2(2)
2 Fact2(1)
1 Fact2(0)
• Infinite recursion
– Occurs if every recursive call results in another
recursive call
– Executes forever (in theory)
– Call requirements for recursive functions
• System memory for local variables and formal
parameters
• Saving information for transfer back to right caller
– Finite system memory leads to
• Execution until system runs out of memory
• Abnormal termination of infinite recursive function
Data Structures Using C++ 2E Edited by Malak Abdullah 17
Jordan University of Science and Technology
Recursive Definitions (cont’d.)
• And so on...
• Fib(10) = . . .
rFibNum(2,3,5) 13
8 5
rFibNum(2,3,4) + rFibNum(2,3,3)
5
rFibNum(2,3,3) + rFibNum(2,3,2) rFibNum(2,3,2) + rFibNum(2,3,1)
rFibNum(2,3,2) + rFibNum(2,3,1) 3 3 2
Fib(4)
Fib(3) Fib(2)
Fib(1) Fib(0) 1 1 0
1 0
Edited by Malak Abdullah
Jordan University of Science and Technology
Fibonacci Number (cont’d.)
5 3 6 2 4
3 6 2 4
6 2 4
2 4
5 3 6 2 4
3 6 2 4
6 4
5 3 6 2 4
3 6
5 6
Largest(arr, 1, 3)
6 , 2, 5
Max = 5
6 > Max ???
0 1 2 3 Largest(arr, 2, 3)
3 6 2 5 2, 5
Max = 5
2 > Max ???
Largest(arr, 3, 3)
5
Edited by Malak Abdullah
Jordan University of Science and Technology
Largest Element in an Array (cont’d.)
• maximum(list[0],
largest(list[1]...list[5]))
• maximum(list[1],
largest(list[2]...list[5]), etc.
• Every time previous formula used to find largest
element in a sublist
– Length of sublist in next call reduced by one
NULL
4 8 9
stackTop
9 8 4
Edited by Malak Abdullah
Jordan University of Science and Technology
Print a Linked List in Reverse Order
(cont’d.)
• Function template to implement previous algorithm
and then apply it to a list
• Object
– Move 64 disks from first needle to third needle
• Rules
– Only one disk can be moved at a time
– Removed disk must be placed on one of the needles
– A larger disk cannot be placed on top of a smaller disk
Fib(4) + Fib(3)
int fib(int a)
{ Fib(3) + Fib(2) Fib(2) + Fib(1)
if(a==1) 1 1 0
return 0; Fib(2) + Fib(1)
if(a==2) 1 0
return 1;
return fib(a-1)+fib(a-2);
}
void main() (((1+0) + 1) + (1+0)) = 3
{
cout<<fib(5)<<endl;
}