Thread: recursion

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    38

    recursion

    I was hoping someone could please walk me through on how this works.

    Code:
    /* Code that accepts a user number and puts it into a function to_binary */
    
    void to_binary(int n)
    {
        int r;
    
        r = n % 2;
        if (n >= 2)
            to_binary(n/2);
        putchar('0' + r);
        return;
    }

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    could you mentally execute the program for
    n = 0, 1, 2, 3, 4... ?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    38
    ok so 0 and 1 i get.. it prints out either 0 or 01

    now lets take 2 for example.. r = 0
    2 is = to 2 so 2 / 2 is 1
    now r =1 r is < 2 so it prints 01

    but thats wrong. how am i looking at this wrong?

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    now r =1 r is < 2 so it prints 01
    No, it calls to_binary(1) before printing the current result, so the final output is '10' as expected.
    Each digit is processed from the left to the right and then everything is printed in the
    reversed order.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  3. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM
  4. To Recur(sion) or to Iterate?That is the question
    By jasrajva in forum C Programming
    Replies: 4
    Last Post: 11-07-2001, 09:24 AM
  5. selection sorting using going-down and going-up recursion
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 02:29 PM