Martin Johnsrud - 1 month ago 5

C++ Question

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`

`n=2`

`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`

`Fib_n=1`

`0`

`#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;

}

Answer

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

Source (Stackoverflow)

Comments