recursion

This is a discussion on recursion within the C Programming forums, part of the General Programming Boards category; I was hoping someone could please walk me through on how this works. Code: /* Code that accepts a user ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,424
    could you mentally execute the program for
    n = 0, 1, 2, 3, 4... ?
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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
    395
    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, 08: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, 09: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, 08: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, 01:29 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21