Fibonacci with C++ Loops

In this tutorial of our C++ course, we will learn how to display the terms of the Fibonacci series, using only loops!

Fibonacci in C++ with FOR

The first two terms in the series are: 0 and 1.
So let's order integers over 2.

Let's store in the last and second variables the last number of the sequence and the last one, initially:
ult = 1
penult = 0

We ask the number for the user and store it in n.
Let's go to our repetition structure, the FOR.

As we have already displayed the first two terms of the sequence: 0 and 1
Our counting starts at the third member of the sequence: aux = 3
And it even goes through n iterations: aux <= n
This ensures that no sequence elements are displayed.

Inside FOR, we first print the next term: ult + penult

Now comes the ace in the hole.
The new value of ult will be the sum of itself with the previous number, penult.
And the new value of penult will be ult.

We want to do this:
penult = ult = 1
ult = 1 + 0 = 1

The problem is that when we do: penult = ult, the original value of penult is lost, which is the old value we would use to calculate the new value of ult.

The solution to this is to store the old penult value in the temp temp variable.
Then just do:
temp = penult;
penult = ult;
ult = ult + temp;

There, now the sequence 'walked', and is ready to display the next term.

See how our code looks:
#include <iostream>
using namespace std;

int main()
{
    int n, aux, temp, ult=1, penult=0;

    cout << "Display how many terms: ";
    cin >> n;

    cout << penult << endl << ult << endl;

    for(aux=3 ; aux<=n ; aux++){
        cout << (ult+penult) << endl;

        temp = penult;
        penult = ult;
        ult = ult + temp;
    }

    return 0;
}

Fibonacci with WHILE in C++

#include <iostream>
using namespace std;

int main()
{
    int n, aux=3, temp, ult=1, penult=0;

    cout << "Display how many terms: ";
    cin >> n;

    cout << penult << endl << ult << endl;

    while(aux<=n){
        cout << (ult+penult) << endl;

        temp = penult;
        penult = ult;
        ult = ult + temp;

        aux++;
    }

    return 0;
}
Can you do with DO WHILE loop, which is calculating as many times as you want, in a loop that only ends when the user enters 0?

Write in the comments.

No comments:

Post a Comment