# fibonacci problem using while loop

• 09-30-2004
galmca
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 ....
• 09-30-2004
Salem
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
• 09-30-2004
Micko
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
• 09-30-2004
xErath
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 :D
• 10-02-2004
xddxogm3
Micko,
The recursion version is pretty sweet.
cubbi.org is a nice website.
• 10-02-2004
nightdancer707
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 :)
• 10-02-2004
aldajlo
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; }```