I am executing a code written in C and it is giving unexpected result which I could not able to figure it out. Why is the value of I printing five times?
Here is
There's nothing wrong with the output.
Since in the fifth call to main nothing happens, the value of i is now still 4, but since you incremented i via i++, i in printf() is now 5 as this is the time i is being used first after the incremention. Printf shows:
5
count is getting incremented via ++count (++count means the value is instantly incremented, so count is now 1). Printf shows:
1
Now the recursive loop ends. For each "level" the line
main();
is done calling, so the next line is
printf("%d\n", i);
since we never change the value of i anymore (because for all "levels" we already incremented i up to 5), the console shows us 5 times the value of 5 for variable i.
The only thing we still change though is the variable count. Since the variable count is still being incremented AFTER the recursive call to main, count still adds up to 5. So the output looks like this:
5 (i, level 5)
1 (count, level 5)
5 (i, level 4)
2 (count, level 4)
5 (i, level 3)
3 (count, level 3)
5 (i, level 2)
4 (count, level 2)
5 (i, level 1)
5 (count, level 1)