C++ program to find Fibonacci series. - coderforcoders

## Wednesday, 13 March 2019

### Fibonacci series program in C++

#### Theory:

Fibonacci series in C++ is a simple program which takes an integer value 'n' as input from the user and prints the first 'n' numbers in the fibonacci series. A fibonacci series is a series of  integer numbers in which each number is the sum of two preceding numbers. For example fibonacci series is 0 1 1 2 3 5 8 13......

#### Logic:

This program uses the concepts of class and objects. Here fibonacci is an user defined class. We need some variables such as n, count, first, second and next to print the first  n numbers in fibonacci series. We have declared the same variables as the data members of the class fibonacci. void printFibo() is a member function of the class fibonacci which displays the first n  numbers in fibonacci series.

{
next=first+second;
first=second;
second=next;
}
cout<<next<<"  ";

#### Program:

C++ program to find Fibonacci series.

#include<iostream>
using namespace std;
class fibonacci{
public:
int n,count,first=0,second=1,next;
void printFibo()
{
cout<<"The first "<<n<<" numbers in fibonacci series are \n";
for(count=0;count<n;count++)
{
if(count<=1)
next=count;
else
{
next=first+second;
first=second;
second=next;
}
cout<<next<<"  ";
}
}
};
int main()
{
fibonacci obj1;
cout<<"Please enter the lenght of fibonacci series \n";
cin>>obj1.n;
obj1.printFibo();
}

Output 1:
Please enter the lenght of the fibonacci series
1
the first 1 numbers in fibonacci series are
0

Output 2:
Please enter the lenght of the fibonacci series
5
the first 5 numbers in fibonacci series are
0 1 1 2 3

Output 3:
Please enter the lenght of the fibonacci series
10
the first 10 numbers in fibonacci series are
0 1 1 2 3 5 8 13 21 34