Print Fibonacci Series in C++

This post will help you to write a program to print Fibonacci series in C++. The first 2 numbers in a Fibonacci series are 0 and 1. Each other term is the sum of previous 2 numbers. i.e the series goes on like: 0 1 1 2 3 5 8 13 and so on..


To implement this in C++, we have 2 variables first and second which are by default 0 and 1 respectively. Each time the loop executes, We print value of first, then set another variable next to sum of first and second. Then we set first to second and second to next, which means we moved on to the next 2 terms. 

Here is the complete program to print n terms in fibonacci series:




Modifications

If n was the limit (and not the number of terms), you could change loop to something like

You can implement the same program in different ways. This program calculates the next 2 terms in advance. You could avoid it if you need. You can also implement this program using recursion. I leave those implementations to you.

Leave a Reply

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