Program in C++ to print nth number of fibonacci series Using Class
FIRST METHOD
#include<iostream> #include<conio.h> using namespace std; class Fibonacci { private: int n; public: Fibonacci(){} Fibonacci(int n1){ n=n1; } ~Fibonacci(){} void input() { cout<<"Enter a number:-"; cin>>n; } void Fibo() { int a=0,b=1,temp,i; for(i=1;i<=n;i++) { if(i==1) cout<<"0 "; else if(i==2) cout<<"1"; else { temp=a+b; cout<<" "<<temp; a=b; b=temp; } } } }; int main() { Fibonacci f1; f1.input(); f1.Fibo(); return 0; }
Output:-
SECOND METHOD
//Programming.OM #include<iostream> #include<conio.h> using namespace std; class Fibonacci { private: unsigned int n,f1,f2,f3; public: Fibonacci(){ f1=0; f2=1; f3=0; } void show() { cout<<"\t"<<f3; } void operator++(int) { f1=f2; f2=f3; f3=f1+f2; } }; int main() { Fibonacci f1; int n; cout<<"Enter a number :"; cin>>n; for(int i=0;i<n;i++) { f1.show(); f1++; } return 0; getch(); }
Output:-
0 Comments