5 Chapter 03 - Recursion+Other Topic
5 Chapter 03 - Recursion+Other Topic
Chapter 3 - Functions
Outline
3.12 Recursion
3.13 Example Using Recursion:
3.14 Recursion vs. Iteration
3.15 Functions with Empty Parameter Lists
3.12 Recursion
• Recursive functions
– Are functions that call themselves
– Can only solve a base case
– If not base case, the function breaks the problem into a
slightly smaller, slightly simpler, problem that resembles the
original problem and
• Launches a new copy of itself to work on the smaller problem,
slowly converging towards the base case
• Makes a call to itself inside the return statement
– Eventually the base case gets solved and then that value
works its way back up to solve the whole problem
3.12 Recursion
• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
5!=5*4*3*2*1=120
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)
void print(int n)
{
if (n<1) return;
cout<<n;
print(n-1);
}
void print(int n)
{
if (n<1) return;
print(n-1);
cout<<n;
}
print(5)
5 <1 ?
print(4)
(4 <1) ?
print(3)
(3 <1) ?
print(2)
(2<1) ?
print(1)
(1 <1) ?
print(0)
0
(0 < 1) return
cout<<n; 1
cout<<n; 2
cout<<n; 3
cout<<n; 4
cout<<n; 5
void function1()
{
cout << "function1 takes no arguments" << endl;
}
Program Output
Local float value of PI = 3.141592741012573242
Global double value of PI = 3.141592653589790007