Articles
Fibonacci Series
C++ | 9/23/2020 8:35:57 AM
Fibonacci Series :
If you get the next number with sum of previous numbers then you can say it is fibonacci series.Let's start
-
-
-
- Finbonacci series with for loop
- Finbonacci series with while loop
- Finbonacci series with recursion
-
-
using namespace std;
#include <conio.h>;
#include <iostream>;
int main()
{
int input;
int fib1 = 0, fib2 = 1, fib3;
cout<<"Please enter number"<<endl;
cin>>input;
cout<<fib1<<" "<<fib2<<" ";
for(int i =2; i < input; i++) //start the loop from 2 because 0 and 1 already printed by intialization
{
fib3 = fib1 + fib2;
cout<<fib3<<" ";
fib1 = fib2;
fib2 = fib3;
}
getch();
return 0;
}
Output : Please enter number
10
0 1 1 2 3 5 8 13 21 34
using namespace std;
#include <conio.h>;
#include <iostream>;
int main()
{
int input;
int fib1 = 0, fib2 = 1, fib3;
cout<<"Please enter number"<<endl;
cin>>input;
cout<<fib1<<" "<<fib2<<" ";
int i =2; //start the loop from 2 because 0 and 1 already printed by intialization
while(i < input)
{
fib3 = fib1 + fib2;
cout<<fib3<<" ";
fib1 = fib2;
fib2 = fib3;
i++;
}
getch();
return 0;
}
Output : Please enter number
10
0 1 1 2 3 5 8 13 21 34
using namespace std;
#include <conio.h>;
#include <iostream>;
void FibonacciSeries(int num, int input, int fib1, int fib2, int fib3)
{
if(num < input)
{
fib3 = fib1 + fib2;
fib1 = fib2;
fib2 = fib3;
cout<<fib3<<" ";
FibonacciSeries(num + 1, input, fib1,fib2,fib3);
}
}
int main()
{
static int input;
static int fib1=0, fib2=1, fib3;
cout<<"Please enter number"<<endl;
cin>>input;
cout<<fib1<<" "<<fib2<<" ";
FibonacciSeries(fib2 + 1, input, fib1, fib2, fib3); //fib2 + 1 because 2 numbers are already inialize
getch();
return 0;
}
Output : Please enter number
10
0 1 1 2 3 5 8 13 21 34