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...
question 1 - how does the printf piece get executed? question 2 - what is the use of getchar() in main body?
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.