Recursion

Process of a function calling itself.

 

Requires a test to get out of the loop - usually an if test.

 

Recursive Factorial example:

#include <iostream>
using namespace std;

int factorial (int i) {

	if (i <=1){return 1;}  //test, to get out of the recursive loop

	int t = i * factorial(i-1) ; //function calling itself

	cout << "Function calling itself on round " << i << ", the factorial is: " << t << endl ;

	return t ;
}

int main() {

	cout << "Please enter a number to calculate its factorial." << endl ;

	int i ;

	cin >> i ;

	cout << endl << "The final factorial of " << i << " is " << factorial(i) << endl ;

	return 0;
}

Compile & Run:

Please enter a number to calculate its factorial.
6
Function calling itself on round 2 , the factorial is:2
Function calling itself on round 3 , the factorial is:6
Function calling itself on round 4 , the factorial is:24
Function calling itself on round 5 , the factorial is:120
Function calling itself on round 6 , the factorial is:720 

 

The final factorial of 6 is 720

 

 

 

And for the famous Fibonacci series example:

#include <iostream>
using namespace std;

int Fibonacci(int i) {
	if (i == 0 || i == 1) {
		return i;
	}

	return Fibonacci(i - 1) + Fibonacci(i - 2);
}

int main() {

	cout << "Please enter the number of iterations for this Fibonacci series: " << endl ;

	int fibs ;
	cin >> fibs ;

	cout << "The Fibonacci series for " << fibs << " items is:" ;

	for (int i = 0; i < fibs; i++){

		cout << " "<< Fibonacci(i) ;

	}

	return 0;
}

Compile & Run:

Please enter the number of iterations for this Fibonacci series:
12
The Fibonacci series for 12 items is: 0 1 1 2 3 5 8 13 21 34 55 89

Leave a Reply