Fibonacci Series Program in C++ | Fibonacci Series Program
This article guide you for making a Fibonacci Series Program in C++. In Fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of Fibonacci series are 0 and 1.
There are two ways to write the Fibonacci series program in C++:
- Fibonacci Series without recursion
- Fibonacci Series using recursion
Fibonacci Series in C++ without Recursion
Letās see the Fibonacci series program without recursion.
#include <iostream> using namespace std; int main() { int a=0,b=1,c,i,number; cout<<"Enter the number of elements: "; cin>>number; cout<<a<<" "<<b<<" "; //printing 0 and 1 for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed { c=a+b; cout<<c<<" "; a=b; b=c; } return 0; }
Output:
Enter the number of elements: 12 0 1 1 2 3 5 8 13 21 34 55 89 Prime Number program in C++.
Fibonacci series using recursion in C++
Letās see the Fibonacci series program using recursion.
#include<iostream> using namespace std; void printFibonacci(int n){ static int a=0, b=1, c; if(n>0){ c = a + b; a = b; b = c; cout<<n3<<" "; printFibonacci(n-1); } } int main(){ int n; cout<<"Enter the number of elements: "; cin>>n; cout<<"Fibonacci Series: "; cout<<"0 "<<"1 "; printFibonacci(n-2); //n-2 because 2 numbers are already printed return 0; }
Output:
Enter the number of elements: 14 Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 Note: If you interested lo learn C++ through web, You can click here.
Conclusion:
Hi guys, I can hope that you can know that how to make Fibonacci Series Program. If you like this post as well as know something new so share this article in your social media accounts. If you have any doubt related to this post then you ask in comment section.