Fibonacci Series with C++ and Python

The term Fibonacci series is used to describe the sequence of numbers generated by a pattern where each number in the sequence is given by the sum of the two preceding numbers. In this article, I will explain how to write a program to print the Fibonacci series with C++ and Python.

What is Fibonacci Series?

Fibonacci numbers were originally used to represent the number of pairs of rabbits born from a pair in a certain population. Suppose a pair of rabbits are introduced to a certain location in the first month of the year. This pair of rabbits will produce a pair of offspring each month, and each pair of rabbits will begin to breed exactly two months after birth. No rabbit ever dies and each pair of rabbits will breed perfectly on time.

So the first month we only have the first pair of rabbits. Likewise, in the second month, we only have our initial pair of rabbits again. However, by the third month, the pair will give birth to another pair of rabbits, and there will now be two pairs. Continuing, we find that in the fourth month we will have 3 pairs, then 5 pairs in the fifth month, then 8,13,21,34, …, etc., continuing in this way. It is quite obvious that this sequence corresponds directly to the Fibonacci sequence, and indeed, it is the first problem ever associated with the now famous numbers.

Fibonacci Series with Python

I hope you now know what is Fibonacci Series and from where it was discovered, now let’s see how to implement it by using the Python programming language:

lastNumber = int(input("Enter last number of series: "))
firstNumber, secondNumber = 0, 1
for i in range(0, lastNumber):
    print(firstNumber)
    firstNumber, secondNumber = secondNumber, firstNumber + secondNumber
Enter last number of series: 10
0
1
1
2
3
5
8
13
21
34

Fibonacci Series with C++

Now, let’s see how to implement the Fibonacci series with C++ programming language:

#include<iostream>
using namespace std;
void fib(int n){
    int t1 = 0;
    int t2 = 1;
    int nextTerm;
    for (int i = 1; i <= n; i++){
        cout<<t1<<endl;
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
    }
    return;
}
int main(){
    int n;
    cin>>n;
    fib(n);
    return 0;
}
10
0
1
1
2
3
5
8
13
21
34

I hope you liked this article on how to print the Fibonacci Series with C++ and Python. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1498

Leave a Reply