# Thread: fibonacci problem using while loop

1. ## fibonacci problem using while loop

hi
i have been working hard on a c program of how to print the first 10 fibonacci numbers?
using while loop....
but i have come out of nothing.... but i know the concept of fibonacci numbers though
but still...i am confused that do i have to declare 10 variables if
after declaring suppose variable 1 as 0 and varaible 2 as 1 then variable 3=varable 1 +variable 2 and i'll be swapping the sum of previous two terms to get a next term as it happens in the series of fibonacci numbers.
plz write a code of this program and help me make me understand using while loop.....
thx ....

2. first = 0;
second = 1;
next = first + second;

Having done that, you shuffle the series
first = second;
second = next;

Now put that lot in a while loop and you're done

3. a little google couldn't hurt:
http://alphasystem.dnsalias.net/Docs.../Examples/C16/

fibonacci.h and fibonacci.cpp
It is C++ but since you're interesting in loops it could be helpful
Or maybe this:
http://cubbi.org/serious/fibonacci/c.html

4. Code:
```int main(){
int f0=0, f1=1, f2=1, i=0;

while(i<10){
/*print the number, and calculate the next one*/
i++;
}
return 0;
}```
Very simple

5. Micko,
The recursion version is pretty sweet.
cubbi.org is a nice website.

6. Recursion version may be sweet, but it's a proved fact that a recursive algorithm of finding fibonacci numbers is WAY slower than an algorithm that is non-recursive (i.e. uses arrays to store the growing fibonacci numbers). Because in the first case, each time a new fibonacci number is calculated, all previous numbers are calculated all over and over again. It may be sweet to read, but for the processor, it's a painful algorithm to work through.

Just thought I'd mention it, in case you don't want to spend minutes finding the 47th or 48th Fibonacci number

7. ## try it

the solution is simple

keep track of two variables term1 & term2
add them and store the resulting value in result
update the variables

Code:
```#include<stdio.h>
#include<conio.h>
int main(void)
{
int result=1,term1=0,term2=1,i=1;
printf("%d ",result);
while(i<10)
{
result = term1 + term2;
printf("%d ",result);
term1 = term2;
term2 = result;
i++;
}
getch();
return 0;
}```