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; }
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
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;
}
}
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;
}