Home > Mobile >  do-while in fibonacci sequence repeating answer
do-while in fibonacci sequence repeating answer

Time:03-05

I made a program about Fibonacci program. I would like to repeat the program so I used do-while loop. However, it seems like the last two numbers from the previous result keep coming. It is supposed to reset back to the first term. Please help me how to get there.

#include<iostream>    
using namespace std;      
void printFibonacci(int n){    
    static int n1=1, n2=1, n3=0;    
    if(n>0){
         n3 = n1   n2;    
         n1 = n2;    
         n2 = n3;    
 cout<<n3<<" ";    
         printFibonacci(n);    
    }    
}    
int main(){    
    int n;    
    cout<<"Enter the number of elements: ";    
    cin>>n;    
    cout<<"Fibonacci Series: ";    
    cout<<"0 "<<"1 ";  
    printFibonacci(n-2);  //n-2 because 2 numbers are already printed    
     return 0;  
}  

CodePudding user response:

When you are running the code for first time, the values of variables t1,t2 and nextTerm are changing. So before repeating the same code again you need to set the default values of those variables again. Simply try this:

#include <iostream>
using namespace std;
int main (){
    int i, n, t1=1, t2=1, nextTerm=0;
    cout << "Fibonacci Program" << endl;
    do{
        t1=1;
        t2=2;
        nextTerm=0;
        cout << "How many elements? ";
        cin >> n;
        if(n>=1){
            cout << "Sequence: ";
            for (int i = 1; i <= n;   i){
                  if(i == 1) {
                    cout << t1 << " ";
                    continue;
                }
                  if(i == 2) {
                    cout << t2 << " ";
                    continue;
                }
                nextTerm = t1   t2;
                t1 = t2;
                t2 = nextTerm;
                cout << nextTerm << " ";
            }
            cout << endl;
        }
        else{
            cout << "Thank you for using the program." << endl;
        }
    }
    while(n>=1);
    return 0;
}

CodePudding user response:

The problem with your code is that you are not resetting your variables after a loop is finished. So to fix this issue, just define your variables inside the do-while loop:

do {
    int t1 = 1, t2 = 1, nextTerm = 0;

..or reset your variables after 1 loop is complete:

else {
    cout << "Thank you for using the program." << endl;
}

t1 = 1, t2 = 1, nextTerm = 0;

But n must be defined outside of loop (as you have done):

std::cout << "Fibonacci Program" << std::endl;

int n;
do {

Also there is no need to create a variable i:

int /*i,*/ t1 = 1, t2 = 1, nextTerm = 0;

..as you have created it later inside the for loop here:

for (int i = 1; i <= n;   i) {

Also, consider not using the following in your code:

using namespace std;

..as it's considered as a bad practice. For more info on this, look up to why is using namespace std considered a bad practice.

  • Related