I am trying to write a code to calculate the nth number in a Fibonacci sequence, where the user enters n in the program interactively.
I have written this code so far, but I have errors when I build and I'm not sure why
#include <iostream>
int main()
{
int x, i, j, n, m;
cout <<"Enter the total number \n";
cin >>n;
cout <<"Total number of the series is \n"<< n;
i=0,j=1;
cout <<i<<j;
for(x=3;x<=n;x++)
{m=i+j;
cout <<"\n"<<m;
i=j;j=m;
}
return 0;
}
i=0,j=1; is wrong. should be semicolon instead of comma:
i=0;
j=1;
also, to ensure consistency in the output, it will be better if you include a line character between the initial i and j as well:
cout <<"\n" << i << "\n" << j;
Thanks. The code successfully builds, but when I start debugging and enter a value, it says that the "j" variable is being used without being initialized?
@coding kid: because its the same as system(). people get into the habit of using it in trivial code and without thinking use that in bigger and bigger programs
#include <iostream>
using namespace std;
int main()
{
int x, i, j, n, m;
cout <<"Enter the total number \n";
cin >>n;
cout <<"Total number of the series is \n"<< n;
i=0;
cout <<"\n" << i << "\n" << j;
j=1;
cout <<i<<j;
for(x=3;x<=n;x++)
{m=i+j;
cout <<"\n"<<m;
i=j;j=m;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int x, i, j, n, m;
cout <<"Enter the total number \n";
cin >>n;
cout <<"Total number of the series is \n"<< n;
i=0;
j=1;
cout <<"\n" << i << "\n" << j;
for(x=0;x<=n;x++)
{m=i+j;
cout <<"\n"<<m;
i=j;j=m;
}
cin.get();
return 0;
}
But when I enter a value once I have debugged, the window closes