I am trying to understand the output of the program printed below. When I look at it, I see that when printnum() is called with an argument of 1, “1” will be printed and then since 1<7, the function will call itself. This process will continue until “6” is printed and then printnum(7) is called. So, now “7” is printed and the if condition is not satisfied, so that code is skipped and we move to the second printf(“%d”, x) function where “7” is printed out again. There is nothing after the second printf(“%d”, x), so why doesn’t everything end there? What makes the program keep going to print the numbers again in descending order?
#include <stdio.h>
int printnum ( int x )
{
printf("%d", x);
if ( x < 7 )
{
printnum ( x + 1 );
}
printf("%d",x);
}
int main()
{
printnum(1);
}
Output:
12345677654321
This happens because the second
printfis called after your recursion exits at each level.As your final recursive call
printfs and ends, control transitions to the function that called it – the second-to-last recursive call. This call then exits the scope of theifstatement, and callsprintf, and then ends – upon which control transitions to the function that called it – the third-to-last recursive call. Repeat until you are inside the call toprintnum(1), whose return takes you back tomain.