Home >>Cpp Programs >Fibonacci Series in C++
Fibonacci Series in C ++ is generally a recurrence sequence in which the next number is the sum of following two numbers, for instance 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. Please note that the first two numbers of Fibonacci series are always 0 and 1.
We can the Fibonacci series program in C++ in two ways that are depicted below:
Here is an example of the Fibonacci series in C++ that is without the recursion that will help you in understanding the topic from a greater depth:
#include <iostream> using namespace std; int main() { int num1=0,num2=1,num3,i,number; cout<<"Please Enter the number of elements you want to print : "; cin>>number; cout<<num1<<" "<<num2<<" "; //First print 0 and 1 for(i=2;i<number;++i) { num3=num1+num2; cout<<num3<<" "; num1=num2; num2=num3; } return 0; }
Here is an example of the Fibonacci series in C++ that is with the use of recursion that will help you in understanding the topic from a greater depth:
#include<iostream> using namespace std; void Fibonacci(int n) { static int num1=0, num2=1, num3; if(n>0) { num3 = num1 + num2; num1 = num2; num2 = num3; cout<<num3<<" "; Fibonacci(n-1); } } int main() { int n; cout<<"Please Enter the number of elements you want to print : "; cin>>n; cout<<"Series are : "; cout<<"0 "<<"1 "; Fibonacci(n-2); return 0; }