educative.io

Educative

Fibonacci Sequence

I compiled this code but its not doing what I thought it would do, I am getting, I thought that the program sequence would break if the input was 0, but its executing everything.

Please let me know what you think

Blockquote
Fibonacci Series upto 1 Terms
1
Fibonacci Series upto 2 Terms
21

indent preformatted text by 4 spaces

#include
#include
using namespace std;

string Fibonacci(int range)
{
string ans = " "; //return the correct string

//int n = 0;
//int k = 0;
string zeroterm = " ";
string firstterm = " ";
string secondterm = " ";

for(int n = range; n<= range; n++){
if((n=0)){
cout << "Fibonacci Series upto " << n << " Terms "<< endl;
zeroterm = to_string(n);
cout << zeroterm << endl;
ans = zeroterm;
}

if((n=1)){

 cout << "Fibonacci Series upto " << n << " Terms "<< endl;
  firstterm = to_string(n);
  firstterm += zeroterm + " ";
  cout << firstterm << endl;
  ans=firstterm;
}

if((n=2)){
cout << "Fibonacci Series upto " << n << " Terms "<< endl;
secondterm = to_string(n);
secondterm += firstterm + " ";
cout << secondterm << endl;
ans=secondterm;
}
//if(n>2){

//}
}
//write your code for genersting fibonacci sequence here
//Hint: Use the concepts from this chapter like loops and if-else statements
return ans;
}

int main(){

Fibonacci(0);

}

Hi Mahesh,

There is a small error in your code due to which you’re not getting the output you expect. In the following lines:

if((n=0)){
cout << "Fibonacci Series upto " << n << " Terms "<< endl;
zeroterm = to_string(n);
cout << zeroterm << endl;
ans = zeroterm;
}

if((n=1)){

 cout << "Fibonacci Series upto " << n << " Terms "<< endl;
  firstterm = to_string(n);
  firstterm += zeroterm + " ";
  cout << firstterm << endl;
  ans=firstterm;
}

if((n=2)){
cout << "Fibonacci Series upto " << n << " Terms "<< endl;
secondterm = to_string(n);
secondterm += firstterm + " ";
cout << secondterm << endl;
ans=secondterm;
}

Change (n=0), (n=1) and (n=2) to (n==0), (n==1) and (n==2) in order to equate the two values. The single equals to sign β€œ=” is used to assign values to a variable. The double equals sign β€œ==” is used to equate the values. So your updated code should be as follows:

if((n == 0)){

cout << "Fibonacci Series upto " << n << " Terms "<< endl;

zeroterm = to_string(n);

cout << zeroterm << endl;

ans = zeroterm;

}

if((n == 1)){

cout << "Fibonacci Series upto " << n << " Terms "<< endl;

firstterm = to_string(n);

firstterm += zeroterm + " ";

cout << firstterm << endl;

ans=firstterm;

}

if((n == 2)){

cout << "Fibonacci Series upto " << n << " Terms "<< endl;

secondterm = to_string(n);

secondterm += firstterm + " ";

cout << secondterm << endl;

ans=secondterm;

}

I hope this clarifies any confusion that you have.

We hope Educative has inspired to further your learning, and please drop us a note if you have any other questions or concerns.

Best regards,
Fatima Bashir
Developer Advocate

1 Like

Thank You Fatima

2 Likes