C++ Program to print Fibonacci Series up to N numbers

Program to print Fibonacci series up to N numbers

Here we will discuss how to find the Fibonacci Series upto n numbers using C++ Programming language.

The user will enter a number and n number of elements of the series will be printed.

The first two elements of the series of are 0 and 1. The next element of the Fibonacci series can be found by adding the previous two elements. 

To find the Fibonacci series upto n numbers we will use a simple loop which will operate on the same principle as mentioned above.

fibannoci series upto n terms in c++

Algorithm:-

  1. User gives an input.
  2. Input is stored in an int type variable say num.
  3. A loop is started to print the Fibonacci series upto num numbers.
    1. For the first two elements of the series 0 and 1 will be printed
    2. For printing more elements next element will be calculated by adding the previous two numbers.
    3. The loop will work until num no of  elements will be printed
  4. The output will be the Fibonacci Series upto num no of terms.
Fibonacci series up to n in C++

C++ Code

 //C++ Program
//Fibonacci Series upto n numbers
#include
using namespace std;
//main program
int main()
{
   // initialising variables
   int limit, first=0, second=1, next, num;
   cout <<"Enter the limit of Fibonacci series"<<endl; // user input cin >> num; 
   cout << "First "<<num<<" terms of Fibonacci series are :- "<<endl;
   //loop for printing fibonacci series
   for(int p=0;p<num;p++)
   {
        if (p <= 1)
           next = p;
        else
        {
             next = first + second;
             first = second;
             second = next;
         }
    cout<<next<<" ";
   }
   return 0;
}

Output

    Enter the limit of Fibonacci series
    10
    First 10 terms of Fibonacci series are :- 
    0 1 1 2 3 5 8 13 21 34