C++: Print Fibonacci Series

Here's an interesting C++ program to start with in the Code. Basically, Fibonacci series is a series of numbers whose succeeding value is obtained by adding the preceding two values. Simple, isn't it? Yeah, it is once the series reaches a 5 or 6 values. Before that, there is quite a little bit complexity while trying to interpret it in the C++ language.

Before that, let me print the Fibonacci series of a few numbers as given below.

0 1 1 2 3 5 8 13 21 34 55 ...

So, I bet you now understood the mechanism of the series. Don't ask me about the start of the series. It's basically like that so as to get the chain. Thus, the series starts with 0 and 1 and the next digit is obtained by adding 0 and 1, i.e, 0+1=1 and then 1+1=2, 1+2=3 and so on. In the first look, yeah, the technique is rather simple. However, you try adding it in the first try and you're most likely to fail if you thought the logic you thought would work. Confusing?

Basically, we can do this by storing the numbers somewhere and later, adding and printing them in a third variable. However, you're most likely to fail if you apply that logic. In most books, I've seen they use the if condition for the first 5 variables and later on, applying the logic. And in some others, they asked users to enter the limit which which should be a minimum of 5, no less. However, if you applied the code in a simple way, you can definitely get the output without any restrictions. Before I talk more, let's move on to the code which is given in the snippet below.

//Program to print the Fibonacci series.
#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int i,limit;
 //Declaring the fibonacci series variables.
 unsigned long int num1=0,num2=1,sum=0;
 cout<<"Enter a limit (number of digits of series): ";
 cin>>limit;
 cout<<"\n";
 //Fibonacci series display code.
 for(i=0;i<limit;i++)
 {
  cout<<sum<<" ";
  num1=num2;
  num2=sum;
  sum=num1+num2;
 }
 getch();
}

You can notice that I used three variables -- namely num1 which is assigned a value of 0 and num2 which is assigned a value of 1 and a sum variable to display the sum which is intially 0. This is because we are going to put the cout statement or else, displaying 0 can be difficult. Since then, the program continues to be in it's pattern.

Thus, we first store num2 in num1, then assigns the value of sum to num2 and then stores num1+num2 in sum and display it, thereby following the pattern of Fibonacci series. Thus, you I'm sure you understood the code I used here. So far, this one is the simplest in my opinion as there is no need of any conditions in order to make this program work.

If you have a better one, do share with me and all other readers. Also, give your feedback to this program. If you are in need of a specific program, don't forget to add the request in the forums and I'll try to dig in and solve it for you. After all, it's just the same human logic. ;)

Advertisements