Caută
  • oanaunciuleanu

Fibonacci Series in C++


The Fibonacci series is a sequence of numbers where one item is the sum of the previous two numbers. The first 2 numbers are 0 and 1, so their sum is 1 and the third element in the row is 1. Now we add 1 and 1 and we get 2, which is the next number. The series is infinite, and it just follows this simple rule.



// Fibonacci series
#include<iostream>
using namespace std;

void fibonacci(int number)
{
    int firstNumber = 0;
    int secondNumber = 1;
    int limit = 1;
    int nextNumber;

    cout << "First " << number << " elements of the Fibonacci series are :" << endl;

   for (int i = 0 ; i < number ; i++)
   {
      if (i <= limit)
      {
          nextNumber = i;
      }
      else
      {
         nextNumber = firstNumber + secondNumber;
         firstNumber = secondNumber;
         secondNumber = nextNumber;
      }
      cout << nextNumber << endl;
    }
}

main()
{
    int number;
    cout << "How many elements from the Fibonacci series do you want to see?" << endl;
    cin >> number;
    fibonacci(number);
}

 
First 10 elements of the Fibonacci series are:
0
1
1
2
3
5
8
13
21
34

© 2018 by The Art Of Coding. by Oana Unciuleanu

This site was designed with the
.com
website builder. Create your website today.
Start Now