🔁 Fibonacci Series Using Recursion in C++
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. In this article, we'll explore how to generate the Fibonacci series using recursion in C++.
📘 What is Recursion?
Recursion is a programming technique where a function calls itself to solve a problem. It is commonly used for problems that can be divided into smaller sub-problems, such as the Fibonacci sequence.
📄 C++ Code: Fibonacci Using Recursion
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
return 0;
}
✅ Sample Output
Enter the number of terms: 6 Fibonacci Series: 0 1 1 2 3 5
📝 How It Works
- The function
fibonacci(n)
calls itself withn - 1
andn - 2
. - Base cases are defined: return 0 if
n == 0
and return 1 ifn == 1
. - This recursive call continues until the base condition is reached for all sub-problems.
📘 Definition: Fibonacci Series Using Recursion
The Fibonacci series using recursion in C++ involves defining a function that returns the sum of the two preceding Fibonacci numbers. The recursion terminates when the base case (0 or 1) is met. Though elegant, recursion may be less efficient for large inputs due to repeated calculations and stack overhead.
🎯 Conclusion
Using recursion to generate the Fibonacci series is a great way to understand recursive thinking and problem breakdown. It is an excellent educational example for beginners and widely used in interviews to assess logical and recursive programming skills.
Post a Comment