Thread: recursion

  1. #1
    Registered User
    Join Date
    Jul 2004
    Posts
    13

    recursion

    hello, this is on a practice test:

    Code:
    void recur (int x) {
       if (x != 0)
          recur(x/2);
    
      printf("%d", x%2);
    }
    It prints out x in binary format, but when I do it by hand I get the binary format backwards. when recur(x/2) is called and x is 1, it prints 1 and then i go back up the tree and print out all the other remainders of 2. what am i doing wrong?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Your printf is at the end of the function. What did you expect it to do, go first? That wouldn't work, because then we'd have ato write all of our functions upside down.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    You simply just have to reverse the order in which printf() comes in due to the nature of recursion. So what I think you want is something like this:

    Code:
    void recur(int x)
    {
         if (x == 0)
            return;
    
         printf("%d",x%2);
         recur(x/2);
    }

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