crecursion

Program Flow explanation in C


Can anyone help me understand the flow of below program? I have mentioned my understanding in below section. Please let me know where I am going wrong.

Objective here is to print 1 to n without using loops using C language. I was able to get this done using goto function but stumbled upon the below solution/code and ran into doubts. Any help is appreciated.

Code

// Prints numbers from 1 to n
void printNos(unsigned int n)
{
    if (n > 0) {
        printNos(n - 1);
        printf("%d ", n);
    }
    return;
}

// Driver code
int main()
{
    int n = 10;
    printNos(n);
    getchar();
    return 0;
}

My understanding...

  1. In the 'main' part (mentioned as Driver code), we define an int by the name of 'n' and give it a value of 10
  2. in the next line we are calling the function 'printNos' and passing the value of of n i.e 10 as an argument
  3. Now program jumps to 'printNos' function and recives the value of n as 10
  4. in the 'printNos' function program reaches the if condition and checks if 10 is greater than 0
  5. If condition turns out to be true and now goes in the body of if function This is where i need help from
  6. Here as per my understanding we are again calling the 'printNos' function with an argument of 10-1 that is 9
  7. As per my understanding this goes in self loop with a new parameter of n-1 i.e 8 then 7 then 6 and so on till n is greater than 0

question 1 - how does the printf piece get executed? question 2 - what is the use of getchar() in main body?


Solution

  • The word you're missing here is "recursive". printNos() is a recursive function, because it calls itself. As is necessary to avoid infinite recursion, it has a condition that permits it to not call itself, which is when n == 0. So what happens is that it builds up a stack of calls to itself, decrementing n each time until it gets to zero. Then it starts returning from each of those calls, which is when each printf() gets executed, in reverse order from how they were stacked. The values of n go on the stack 10, 9, ..., 1, and then come off the stack and are printed 1, 2, ..., 10.

    As for the getchar(), that pauses the program until a character is provided as input. I have no idea why that's in there.