In this tutorial, we will write a Fibonacci Series program in C++ u. Before that, you should have knowledge of the following topic in C++.
Fibonacci series is the series of numbers where the next number is achieved by the addition of the previous two numbers. The initial addition of two numbers is 0 and 1. For example: 0, 1, 1, 2, 3, 5, 8, 13….,etc.
Recursion refers to the process when a function calls itself inside that function directly or indirectly or in a cycle.
If you want to learn more about recursion in detail, click here. Although it is for C programming, the theory concept of recursion is the same for all programming languages.
Fibonacci series using Recursion in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <iostream> using namespace std; void recurFunc(int); //function prototype int main() { int num; cout << "Enter the number of elements: "; cin >> num; cout << "Fibonacci Series: "; cout << "0 " << "1 "; //calling function //since two numbers are alredy printed so (n-2) recurFunc(num - 2); return 0; } void recurFunc(int n) { static int term1 = 0, term2 = 1, next; if (n > 0) { next = term1 + term2; term1 = term2; term2 = next; cout << next << " "; recurFunc(n - 1); } } |
Output:
Enter the number of elements: 5
Fibonacci Series: 0 1 1 2 3
You may go through the following: