you have used main function as a recursive function thus when you call it with argument 1 it will stack main function while k reach the value of 10, then it dequeue the stack and print values by reverse order. you pass ,2,3,..10 and after dequeue of stack it will print 10,9,..2
Output of following program
-
22-09-2022 - |
Question
#include <stdio.h>
int main(int k)
{
if(k<10)
printf("%d ",main(k+1));
return k;
}
output is:
10 9 8 7 6 5 4 3 2
In arguments of main()
function, its argc
but how is it used here?
Solution 2
OTHER TIPS
First your signature of main
is what standard defines it. Your compiler should give warning:
[Warning] 'main' takes only zero or two arguments [-Wmain]
C11: 5.1.2.2.1 Program startup:
The function called at program startup is named
main
. The implementation declares no prototype for this function. It shall be defined with a return type ofint
and with no parameters:int main(void) { /* ... */ }
or with two parameters (referred to here as
argc
andargv
, though any names may be used1,as they are local to the function in which they are declared):int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
Now, you can give any name to argc
and argv
. Here argc
is k
. Since you are passing no parameter to main
the value of k
is 1
because here argv[0]
is the name of the program. Now k=1
is used by the program as initial value and the value
10 9 8 7 6 5 4 3 2
is printed by recursive call of main
.
1. emphasis is mine.