samedi 5 mars 2022

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;
int main (){
    int i, n, t1=1, t2=1, nextTerm=0;
    cout << "Fibonacci Program" << endl;
    do{
        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;
}

Aucun commentaire:

Enregistrer un commentaire