# Fibonacci series - a different way

I am a C++ student (1.5 months into it). Please give feedback to this different way I have thought of for Fibonacci series. If there are any improvements needed, please suggest them also.

#include<iostream>
using namespace std;
void fibseries(long int n)
{
double x=0;double y=1;
for (long int i=1;i<=n;i++)
{
if(i%2==1)
{
cout<<x<<" ";
x=x+y;
}
else
{
cout<<y<<" ";
y=x+y;
}
}
}
main()
{
long int n=0;
cout<<"The number of terms ";
cin>>n;
fibseries(n);
return 0;
}

• Please disclose what you are trying to achieve (coding this the way you chose, not what the code is supposed to be good for). (Please develop a habit of documenting/commenting code - have a look at doxygen.) – greybeard Jun 3 '17 at 21:21
• Please do not update the code in the post after receiving questions, as it invalidates previous answers. If you would like to ask for review of improved version, please ask a follow up question. – Incomputable Jun 4 '17 at 5:25
• Ok,thanks for your valuable comments.I will look out for this and make my coding style better. – Jittin Jun 4 '17 at 12:02

1. You should change this double x=0;double y=1; add newline after first ;
2. Using ++i is a best practice no matter if the type is int, so use ++i instead i++ and learn difference between them.
3. change main to int main, It is required to be standard compliant.
4. Why do you use doubles as x and y. Fibonacci numbers are always integers.
5. There are many fibonacci algorithms, you can look here

https://stackoverflow.com/questions/14661633/finding-out-nth-fibonacci-number-for-very-large-n

http://fusharblog.com/solving-linear-recurrence-for-programming-contest/

• I used double x and y because even with long int,the series will only continue upto 47th value and after that it will start showing wrong values(wrong values are shown because the values are beyond the int range). – Jittin Jun 4 '17 at 3:11
• @Jittin Are you familiar with the different data types and their ranges in C++? This might help you. – yuri Jun 4 '17 at 7:30
• I am new,but I feeel fine with the range.I don't get your point.The range for int will get over by the 47th terms of the series.@yuri – Jittin Jun 4 '17 at 11:54
• @Jittin Although double can continue with approximate values hundreds of digits long, it will start producing inaccurate results as soon as values are more than 15 digits. It's not as obvious as when int values overflow; but they're wrong nonetheless, and become more inaccurate as you proceed through the sequence. However, if you use a 64-bit integer type, the range supported is up to 20 digits; and results will be accurate for that full range. If you want longer sequences, then you should use a "big int" library supporting arbitrary sized integers. But stick to integers! – Disillusioned Jun 6 '17 at 1:06