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