Site icon T4Tutorials.com

C++ program Fibonacci series using class inheritance

What is fibonacci series Formula

Write a program in C++ to display the first n terms of the Fibonacci series by using the class. The series is as follows: Fibonacci series 0 1 2 3 5 8 13.

#include<iostream>
using namespace std;
class series
{
	public:
		int a,b,t,j,num;
		public:
			int input()
			{
				a=0,b=1;
				cout<<"enter the number : "<<endl;
				cin>>num;
				cout<<"the fb series is : "<<a<<b;
				
			}
			int show()
			{
				for( j=3; j<=num; j++)
				{
					t=a+b;
					cout<<t;
					a=b;
					b=t;
				}	
			}
		};
			int main()
			{
				series obj;
				obj.input();
				obj.show();
		    }
						

WAP in C++ to display the Fibonacci series by using the single inheritance.

#include<iostream>
using namespace std;
class series 
{
	protected:
	int a,b,t,j,num;
};
class child:public series
{
	public:
		int input()
		{
			a=0;
			b=1;
			cout<<"enter the number : "<<endl;
			cin>>num;
			cout<<"the fb series is : "<<a<<b;
		}
		public:
			int show()
			{
				for(j=3; j<=num; j++)
				{
					t=a+b;
					cout<<t;
					a=b;
					b=t;
				}
			}
};
int main()
{
	child obj;
	obj.input();
	obj.show();
}

C++ program to show the Fibonacci series by using the multi-level inheritance.

#include<iostream>
using namespace std;
class series1
{
	protected:
		int a,b,num;
};
class series2:public series1
{
	protected:
		int t,j;
};
class series3:public series2
{
	public:
		int input()
		{
			a=0;
			b=1;
			cout<<"enter the number : "<<endl;
			cin>>num;
			cout<<"the fb series is : "<<a<<b;
		}
		public:
			int show()
			{
				for(j=3; j<=num; j++)
				{
					t=a+b;
					cout<<t;
					a=b;
					b=t;
				}
			}
};
int main()
{
	series3 obj;
	obj.input();
	obj.show();
}

 

Exit mobile version