0

What is wrong in this code for Fibonacci series?Please explain.

#include <iostream> using namespace std; int main() { int a=0,b=1,sum,n,c; cout<<"Enter the number of terms"<<endl; cin>>n; cout<<a<<endl; cout<<b<<endl; for(c=0;c<=n;c++) while (c<=n) sum=a+b; a=b; b=sum; cout<<sum<<endl; return 0; }

15th Dec 2016, 6:19 PM
Rithvik Shindihatti
Rithvik Shindihatti - avatar
3 Respostas
+ 1
First - use only one loop The initial value for c should be 1 Declare loop within curly brackets and the most important b=a and a =sum. Remember the order or you'll get bogus value
15th Dec 2016, 6:38 PM
Himesh Gangrade
0
void fibo(int n) { int t, a = 0, b = 1; cout << a; for(int i=0; i<=n; i++) { cout << "," << b; t = a; a = b; b += t; } }
15th Dec 2016, 8:25 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
Rithvik, Try correcting the following: -Add opening and closing brackets to for loop. All loop actions should be within brackets. -Remove while loop since condition is implied in for loop ((c<=n)) Final code should look like this: --------- #include <iostream> using namespace std; int main() { int a=0,b=1,sum,n,c; cout<<"Enter the number of terms"<<endl; cin>>n; cout<<a<<endl; cout<<b<<endl; for(c=0;c<=n;c++){ sum=a+b; a=b; b=sum; cout<<sum<<endl; } return 0; }
15th Dec 2016, 11:54 PM
Amber Adams
Amber Adams - avatar