Print Fibonacci series in C++

In this page we will Print Fibonacci series in C++ but before starting program what is Fibonacci series ?

In Fibonacci series, the first number and the second number are total, is the third number.

first number + second number = third number

such as,

Here is the program,

#include<iostream>
using namespace std;

int main()
 {
  int first=0,second=1,next;
  int num;
  clrscr();
 
   cout<<"Enter the number of terms in series:"; 
   cin>>num;

   cout<<first<<"\t"<<second;

  int i=3;
  while(i<=num)
  {
     next=first+second;
     cout<<"\t"<<next; 
     first=second; // now first number is second
     second=next; // and second number is next
     i++;        
  }
return 0;
}

OUTPUT

Enter the number of terms in series: 8
0       1       1       2       3       5

Explanation

In the program, we have declared the following variables.

int num, first,second,next;

In which variable first and wearable seconds have been initialized and variable numbers have been used to store user input.

Suppose user input is 8

num =8;

First of all we have printed the value of variable first and variable second.

After this the loop starts.

We have assigned the value 3 to the variable i here because we have already printed in two terms(variable first and second) of the series.

if your are interested then here is the complete process To Print Fibonacci series in C++​,

in first first = 0 second = 1 i =3

while(3<=8) 
 {
   next = first+second; //0+1;
   cout<<next; // 1
   first = second; //1
   second = next//1
   3++; // 4
 }

now first =1 , second =1 i =4

while(4<=8) {
   next = first+second;//1+1
   cout<<next;// 2
   first = second; // 1
   second = next//2
   4++; // 5
}

now first =1 second =2 i =5

while(5<=8) {
   next = first+second;//1+2
   cout<<next;// 3
   first = second; // 2
   second = next//3
   5++; // 6
}

now first = 2 second =3 i =6

while(6<=8) {
   next = first+second;//2+3
   cout<<next;// 5
   first = second; // 3
   second = next//5
   6++; // 7
}

now first = 3 second =3 i =7

while(7<=8) {
   next = first+second;//3+5
   cout<<next;// 8
   first = second; // 5
   second = next//8
   7++; // 8
}

now first = 5 second = 8 i =8 and in last execution 13 will be print as above manner

in the value of variable i increase by 1 so its become 9 so condition will be such as,

while( 9<=8)

which becoming false so loop will be terminate and we get the following output,

0 1 1 2 3 5 8 13

Related exercise


C++ Examples

Like it?

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version