Thread: Recursion Question

  1. #1
    Registered User
    Join Date
    Mar 2018
    Posts
    1

    Recursion Question

    Hey, so I'm obviously new here, working my way through this book. I basically understand recursion, but I don't understand part of it. Can someone explain to me in plain terms what happens in the following code such that it works?

    Code:
    void pb (int n)
    {
        if (n != 0) {
            pb (n / 2);
            putchar('0' + n % 2);
        }
    }
    So please help me understand what's happening here. Seeing as it does in fact work (printing n's binary form), it is easy to see how that would happen. But, the way I (incorrectly) see it, it just runs like this: Let's say main calls pb(55). I see pb recursively calling itself until n finally goes from 1 to 0, never reaching the putchar statement​. At which point pb(0) is called--n == 0 so the if statement would not be entered. And that would be the end. Obviously that is not in fact what happens. Clearly I have some fundamental misunderstanding. Basically, why and how the putchar statement is executed. Thanks in advance for your help!

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    You're correct up to the point where you said "and that would be the end"; it's only the end of the beginning (to coin a phrase).

    At that point, call after call has occurred, building the stack frames higher and higher (or digging them lower depending on how you want to look at it), and that's the state of things when pb(0) finally doesn't do the recursive call but instead ... RETURNS!

    Back up (or is it down?) the call stack we go. Each of those calls returns, IN REVERSE ORDER, printing it's bit. That is of course the order that the bits need to be printed, so it works out noicely.
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. a question about recursion
    By lazyme in forum C Programming
    Replies: 4
    Last Post: 02-28-2011, 01:54 PM
  2. recursion question
    By sumdude in forum C Programming
    Replies: 11
    Last Post: 10-06-2008, 02:52 PM
  3. Question about recursion
    By tjpanda in forum C++ Programming
    Replies: 3
    Last Post: 09-10-2008, 06:25 AM
  4. Another question about recursion
    By Jacquiline in forum C Programming
    Replies: 2
    Last Post: 04-06-2003, 08:25 AM
  5. Question about recursion
    By Imperito in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 04-03-2002, 12:51 PM

Tags for this Thread