View Single Post
  #3 (permalink)  
Old February 23rd, 2004, 08:09 PM
nikolai nikolai is offline
Friend of Wrox
 
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Quote:
quote:Originally posted by amahja56
for(i=2;i<n;i++)
{
    c = a + b;
    cout << " " << c;
    a = b;
    b = c;
}
Well, the Fibonacci sequence is one where each successive number in the sequence is the sum of the two previous numbers:

0 1 1 2 3 5 8 13...

Starting with 2, notice that:

Code:
   2 = 1 + 1,
   3 = 1 + 2,
   5 = 2 + 3
   8 = 3 + 5
  13 = 5 + 8

   c = a + b   <--  This is the pattern using the variable names
                    defined in your for loop.
So basically what your loop is doing is calculating the current number, c, as the sum of the two previous numbers, a and b.

Once you output the value of c, then you set up your numbers for the next iteration.

The old value of b becomes the new value of a. The old value of c becomes the new value of b.

Thus, a and b are the two most recent consecutive numbers of the sequence. The next iteration will reassign the value of a + b to c, yielding the next sum in the series.


Often it makes everything a LOT more readable if you use proper indentation and spacing.


Take care,

Nik
http://www.bigaction.org/
Reply With Quote