Why does my code work? Simple arithmetics

int Fib_1;
int Fib_2;

were never initialized. Therefore, the first time you calculate Fib_n=Fib_1+Fib_2;, Fib_n will get the sum of two uninitialized variables.

I have modified your code so it would work.

#include <iostream>

using namespace std;

int main()  
    cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;

    int n;
    cin >> n;
    cout << endl;

    int Fib_1 = 1;
    int Fib_2 = 1;

    int count = 0;

    while(n > count)
        Fib_1 = Fib_1 + Fib_2;
        Fib_2 = Fib_1 - Fib_2;

    cout << Fib_1;
    return 0;

Browse More Popular Posts

Leave a Comment