Recursive functions in C and printf

后端 未结 2 1946
無奈伤痛
無奈伤痛 2021-01-26 23:20

So, first of all I\'m a total beginner in C, we\'re studying it at University on the course \'Structured Programming\'.

Now, the last few lectures about \'Recursive func

2条回答
  •  无人及你
    2021-01-26 23:44

    The reversal is done using the call stack of the functions. By that I mean that the way the functions are called, this guarantess that the MSB will be printed first then the next one and so on.

    void binary(int num)
    {
        if (num == 0) return;
    
        binary(num / 2);  // Wait, I will print but you first print the MSB's.
        printf("%d", num % 2); // Now I print the last digit.
    }
    

    Downward motion moves the calls.

    {binary(12)                     
       {binary(6)                 
          {binary(3)        
            {binary(1)  
                 binary(0) -- returns
            Now we print 1
            }
          print 1
          }
       prints 0
       }
    prints 0
    }
    

提交回复
热议问题