This particular Code was made on Dcoder on Android... My question is,How am I still able to execute it if my input for n is less than 6..(Condition i>=6 is not fulfilled for the for loop right..)Also using this code I always get the answer as 1,2,3,5,8... and the number of terms printed is always more than the input of n..
Also I tried putting i<=0 but I get the same results...
#include <iostream>
using namespace std;
int a=0,b=1,x,i,n;
int main()
{
cout<<"This Program Gives You The List Of First 'n' Fibonacci Numbers:"<<endl
<<"Enter The Value Of 'n':"<<endl;
cin>>n;
if(n<1)
{
cout<<"Invalid Input"<<endl<<"Please Restart This Program And Enter A Natural Number."<<endl;
}
else
{
cout<<"The First "<<n<<" Fibonacci Numbers Are:"<<endl;
for(i;i>=6,i<=n;i++)
{
x=a+b;
a=b;
b=x;
cout<<x<<endl;
}
}
return 0;
}
But surprisingly the code below works..Why? And What is the fundamental difference between the two except that I intentionally print 0 and 1 in the second code...?Also I didn't find any difference when I used post increment and pre increment in my For Loop..Why?Also It would be really helpful to get some examples which behave differently with post and pre increment...
#include <iostream>
using namespace std;
int a=0,b=1,x,i,n;
int main()
{
cout<<"This Program Gives You The List Of First 'n' Fibonacci Numbers:"<<endl
<<"Enter The Value Of 'n':"<<endl;
cin>>n;
if(n<1)
{
cout<<"Invalid Input"<<endl<<"Please Restart This Program And Enter A Natural Number."<<endl;
}
else
{
cout<<"The First "<<n<<" Fibonacci Numbers Are:"<<endl;
cout<<"0"<<endl<<"1"<<endl;
for(i;i>=0,i<=n-2;i++)
{
x=a+b;
a=b;
b=x;
cout<<x<<endl;
}
}
return 0;
}
Your use of the comma operator is a problem and is leading you to believe that the condition is actually enforced.
This statement
i>=6,i<=n;
ignores the result (false
if n==6
) from i>=6
, despite evaluating it and then proceeds to check if i<=n
because that's how the comma(,
) operator works in this context. Thus your loop still prints values when n
is <=6
. What you are looking for is
i>=6 && i<=n;
The &&
is the Logical AND operator which means that both the conditions need to be true for the statement to be true (and doesn't discard the Left Hand Side condition obviously).
As for why that loop runs for 7 times (one more than n
if n
is 6) that's because your loop essentially becomes:
for(i = 0; i <= 6; i++)
which shall run 7 times, starting from 0.
The same thing happens with your second piece of code, only this time that loop is essentially
for(i = 0; i<= n- 2;i++)
So, for a value of n
as 6, you would have 5 iterations, which is what you see, i.e. the 5 terms after 0 and 1
This Program Gives You The List Of First 'n' Fibonacci Numbers:
Enter The Value Of 'n':
The First 6 Fibonacci Numbers Are:
0
1
1
2
3
5
8