Beruflich Dokumente
Kultur Dokumente
Tutorial 6
Intro to Recursion
Recursion basics
By definition, a recursive function is a function that calls itself until a
certain condition is met. That condition is called the base case.
The best practice of recursion is to see a lot of examples and practice.
Lets see an example that will recursively print out the numbers from 1
to 5.
Example 1:
Recursive print
#include <iostream>
using namespace std;
void Print(int n){
if(n < 1) return;
Print(n-1);
cout << n << endl;
};
int main(){
Print(5);
return 0;
}
Recursive tracing
www.cstutoringcenter.com
When recursive functions are being called, they are placed on what is
called the runtime stack of a program. Just the same as a stack of
dishes, the item on the top is the item that is accessed. With a
program, it is the same idea that the most recent call to the stack is
the currently active function call.
Here is the trace for the above printing example. It shows the call of
the function and the value of n.
Print(5)
Print(4)
Print(3)
Print(2)
Print(1)
Print(0) <-- base case here.
Print(1) <-- prints 1
Print(2) <-- prints 2
Print(3) <-- prints 3
Print(4) <-- prints 4
Print(5) <-- prints 5
Example 2:
Triangle of Stars Recursion
#include <iostream>
using namespace std;
void Triangle(int x) {
if (x <= 0) return;
Triangle(x - 1);
for (int i = 1; i <= x; i++)
cout << "*";
cout << endl;
}
int main() {
Triangle(7);
return 0;
}
www.cstutoringcenter.com
Triangle(1)
Triangle(0) <-- base case
Triangle(1) <-- prints 1 star & new line
Triangle(2) <-- prints 2 stars & new line
Triangle(3) <-- prints 3 stars & new line
Triangle(4) <-- prints 4 stars & new line
Triangle(5) <-- prints 5 stars & new line
Triangle(6) <-- prints 6 stars & new line
Triangle(7) <-- prints 7 stars & new line
Example 3:
Factorial recursion
#include <iostream>
using namespace std;
int fact( int n ){
//base case:
if( n <= 1 ) return 1;
return n * fact(n-1);
}
int main(){
cout << fact(4) << endl;
return 0;
}
Proof Recursively:
www.cstutoringcenter.com
In the above main function, we are trying to find the factorial of the
integer 4. Using the rule of the factorials, the answer should be 24
since 4x3x2x1 = 24. Applying the function and passing in 4 as the
parameter, here is the tree:
Fact(4)
4* Fact(3)
3* Fact(2)
2* Fact(1)
2* 1 <-- 2
3* 2 <-- 6
4* 6 <-- 24
www.cstutoringcenter.com