Martin Johnsrud - 1 year ago 64
C++ Question

# Why does my code work? Simple arithmetics

I am writing a simple code to calculate Fabonacci numbers as an exercise. The code works, but i don't get why. I have some special cases for

`n=1`
and
`n=2`
which is the place of the number in the sequence (the numbers are 0 and 1). However after those, the number is calculated in this loop.

``````while(n>LoopCount)
{

Fib_n=Fib_1+Fib_2;

Fib_2=Fib_1;

Fib_1=Fib_n;

LoopCount++;
}
``````

Going in to the loop,
`Fib_1=0`
,
`Fib_2=0`
, and
`Fib_n=1`
. Why does not this loop just spit out
`0`
no matter what? The whole code is below.

``````#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_n;
int Fib_1;
int Fib_2;
int LoopCount=1;

if(n>1)
{
Fib_n=1;
LoopCount++;

while(n>LoopCount)
{

Fib_n=Fib_1+Fib_2;

Fib_2=Fib_1;

Fib_1=Fib_n;

LoopCount++;
}
}

cout <<Fib_n;

return 0;
}
``````

``````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;
count++;
}

cout << Fib_1;
return 0;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download