Fibonacci Series in cpp

Fibonacci Series in cpp simple program which is implemented using different method in cpp.

In this tutorial we are going to leans  what is Fibonacci series , Fibonacci series algorithm, Fibonacci series in cpp.

what is Fibonacci :

Fibonacci is a series of numbers starting from 0 and adding with two numbers before it.

Fibonacci series logic

Logic is  : Fibonacci series is a collection or set of the numbers starting with zero or one, followed by the sum of two preceding numbers.

consider Fibonacci series till N which is implemented as 0,1,(0+1),(0+2)…. N.

Example :

Write Fibonacci series up to 8 numbers.

0,1,1,2,3,5,8,13.

we calculated this series as first two number as 0 and 1 , 0+1 => 1, 1+2=>3 ,3+2=>5,5+3=>8,8+5=>13

Algorithm to  Print Fibonacci series

  1. Start
  2. Declare variables
  3. Take N from user
  4. Using for loop print sries
  5. End

Fibonacci series  using for Loop 

This is the one method to print the Fibonacci series.

In this, we use the for loop to iterate number to range up to which we want to print the Fibonacci series.

C++ Program to Display Fibonacci Series

12345678910111213141516171819202122#include <iostream>using namespace std;int main(){ int i, n, t1 = 0, t2 = 1, nextTerm;    cout<<“Enter the number of terms: “;   cin>>n;    cout<<“Fibonacci Series: “;    for (i = 1; i <= n; ++i)    {cout<<t1<<” “;        nextTerm = t1 + t2;        t1 = t2;        t2 = nextTerm;    }    return 0;}

Output :

Fibonacci Sequence
Fibonacci Sequence

Explanation :

1. Execution of the program starts with the main function.

2. Declare variables

i, n, t1, t2 ,1, nextTerm

3. Take N value that is how many series user want

cin>>n;

=> n= 3

4.  Now the main logic begins

for (i = 1; i <= n; ++i) => we write for loop to print series

At iteration 1

i=1, 1<=3

cout<<t1<<” “; => t1 = 0 printed

nextTerm = t1 + t2;  =>nextTerm = 1

t1 = t2; => t1= 1

t2 = nextTerm; => t2=1

At iteration 2

i=2, 2<=3

cout<<t1<<” “; => t1 = 1  printed

nextTerm = t1 + t2;  =>nextTerm = 2

t1 = t2; => t1= 1

t2 = nextTerm; => t2=2

At iteration 3

i=3, 3<=3

cout<<t1<<” “; => t1 = 1 printed

nextTerm = t1 + t2;  =>nextTerm = 3

t1 = t2; => t1= 2

t2 = nextTerm; => t2=3

At iteration 4

i=4, 4<=3  condition false

5. End with the program.