'do-while in fibonacci sequence repeating answer

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


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Solved Games