Thread: Fibonacci numbers in C

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    26
    <<split from here>>

    I have a question about the following code:

    Code:
    int x = 0, y = 1, z;
      int i;
    
      for ( i = 0; i < 10; i++ ) {
        printf ( "F(&#37;d): %d\n", i, x );
        z = x + y;
        y = x;
        x = z;
      }
    I switched the values for x and y so the sequence would display 0 as the first.

    I understand everything except

    Code:
    z = x + y;
    y = x;
    x = z;
    So when it runs through the first time, z becomes 0+1=1. but what I don't understand is how y=x and x=z..

    It seems to me that x equals 0, making y =0, then making z, which is 1 equal x. So you have 0 and 1 again.

    Can anyone explain to me the logic of this sequence?

  2. #2
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Y gets copied to X, so the smallest number is lost. Z gets copied to Y so the last number result is stored. IE:
    Code:
    x    y     z
    0 + 1 = 1
    1 + 1 = 2
    1 + 2 = 3
    2 + 3 = 5
    3 + 5 = 8
    5 + 8 = 13
    [edit]Oh yeah changed the variable names around in my explanation, but I hope at least it helps explain what your output should look like.
    Last edited by mike_g; 09-28-2007 at 05:32 PM.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    26
    Yeah, that makes sense. Thanks mike

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fibonacci numbers (using class)
    By -chr- in forum C++ Programming
    Replies: 3
    Last Post: 01-21-2009, 04:49 PM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. Fibonacci numbers in C
    By Alastor in forum C Programming
    Replies: 23
    Last Post: 10-10-2005, 01:45 PM
  4. the definition of a mathematical "average" or "mean"
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 12-03-2002, 11:15 AM
  5. FIBONACCI NUMBERS, please help!
    By JamesAnthony23 in forum C Programming
    Replies: 5
    Last Post: 09-26-2002, 03:39 PM