# Fibonacci Questoin

• 09-10-2011
drumerboy3841
Fibonacci Questoin
Hey guys first post here. I just switched my major to computer science last semester. So first my c++ class and this would be my second assignment. I need to write a function(in the from of a program for testing purposes) that prints the all the Fibonacci numbers less than 30,000. So my below code does all this except it prints one number after 30,000. Can anyone give me some idea on how to fix it? Or maybe a better a better way to implement it with a for loop? Thanks a ton in advance.

Code:

```#include<iostream> using namespace std; int main() {         //Declaration         unsigned int fib1=0, fib2=1, fib3=0;                 //fibonacci loop         while(fib3<30000)         {                 fib3=fib1+fib2;                 cout<<fib3<<endl;                 fib1=fib2;                 fib2=fib3;         }         return(0); }```
• 09-10-2011
AndrewHunter
Quote:

Originally Posted by drumerboy3841
Code:

```#include<iostream> using namespace std; int main() {         //Declaration         unsigned int fib1=0, fib2=1, fib3=0;                 //fibonacci loop         while(fib<30000)         {                 fib3=fib1+fib2;                 cout<<fib3<<endl;                 fib1=fib2;                 fib2=fib3;         }         return(0); }```

My guess is that it has something to do with your while loop. However I can't tell since fib doesn't exist. Assuming you intended fib3 note when during your loop fib3 exceeds 30,000. It is after you print it. Just move your summation to the last line in the loop.
• 09-10-2011
drumerboy3841
oops i just copied wrong :/ it was supposed to be (fib3<30000). but ill give it a try switching the summation. thank you.
• 09-11-2011
drumerboy3841
Well all i did was move the cout line to the top of the loop and it fixed the problem. thanks a lot. but out of curiosity; the fib3=fib1+fib2 doesn't really seem to do anything, since, at then end of the loop fib3 is reassigned anyways.... So why does the program give me an unlimited amount of 000000 when i delete that line and run it??

Code:

```#include<iostream> using namespace std; int main() {         //Declaration         unsigned int fib1=0, fib2=1, fib3=0;                         while(fib3<30000)         {                 cout<<fib3<<endl;                 fib3=fib1+fib2;                 fib1=fib2;                 fib2=fib3;         }         return(0); }```
• 09-11-2011
anon
It's not reassigned at the end of the loop. That line is the only one that assigns to fib3.
• 09-11-2011
GReaper
@anos's right. Why would you think that?
• 09-11-2011
drumerboy3841
Because I was sleep deprived and blind when I was looking at it :/ thanks guys haha