Examples of Recursion in C++
The following examples will improve the understanding of C++ recursion:
Example 1: Fibonacci Series using Recursion
// C++ Program to find fibonacci series using recursion
#include <iostream>
using namespace std;
// Function for fibonacci
int fib(int n)
{
// Stop condition
if (n == 0)
return 0;
// Stop condition
if (n == 1 || n == 2)
return 1;
// Recursion function
else
return (fib(n - 1) + fib(n - 2));
}
// Driver Code
int main()
{
// Initialize variable n.
int n = 5;
cout << "Fibonacci series of 5 numbers is: ";
// for loop to print the fibonacci series.
for (int i = 0; i < n; i++) {
cout << fib(i) << " ";
}
return 0;
}
Output
Fibonacci series of 5 numbers is: 0 1 1 2 3
In this example, the Fibonacci function calls itself with smaller inputs (n – 1 and n – 2) until it reaches the base case (n <= 1) and returns a value.
Example 2: Print Array in reverse order using recursion.
// C++ Program to print array using
// recursion
#include <iostream>
using namespace std;
// recursive function to print array
void pArray(int* arr, int n)
{
// base condition
if (n == 0) {
return;
}
// recursive call
cout << arr[n - 1] << ' ';
pArray(arr, n - 1);
}
int main()
{
// declaring array
int arr[5] = { 1, 2, 3, 4, 5 };
// calling function
pArray(arr, 5);
return 0;
}
Output
5 4 3 2 1
C++ Recursion
Assume that you have to paint a few balls. If you do it alone, it will take a lot of time. One thing you can do is to take help from your friend. Assuming that you have the same work speed, the task will be done in half of the time. Now, instead of taking help from only one of your friends, you take help from multiple friends such that each friend have only one ball to paint. The task will be done much faster as compared to when you were doing it alone. Recursion is a problem-solving technique that works in a similar way.