这可能是你想要的吗?
#include <stdio.h>
void print(int n)
{
int i;
if (n > 0) // [2]
{
//call print recursively
print(n-1); // [3]
for (i=1; i<=n; i++) // [4]
printf("%d",i);
printf("\n");
}
}
int main(int argc, char *argv[])
{
// If no argument, default to 8
int value=8;
if (argc > 1 )
value = atoi(argv[1]);
print(value); // [1]
return 0;
}
编译它并像这样执行:
display 3
或不带任何参数(默认为display 8
):
display
诀窍是print(n-1)
在打印当前的输出之前调用n
。这是执行时的程序流程display 3
:
<main() function is running>
main() calls print(3) in [1]
<print(3) is running, n is 3>
since n>0 in [2] print(3) calls print(2) in [3]
<print(2) is running, n is 2>
since n>0 print(2) calls print(1)
<print(1) is running, n is 1>
since n>0 print(1) calls print(0)
<print(0) is running, n is 0>
since n=0 print(0) doesn't print anything and returns
now the function that called print(0) (that is, print(1)) takes over
<print(1) is running, n is 1, continues executing in [4]>
print (1) enters the for loop, prints "1\n" and returns
now the function that called print(1) (that is, print(2)) takes over
<print(2) is running, n is 2, continues executing in [4]>
print(2) enters the for loop, prints "12\n" and returns
now the function that called print(2) (that is, print(3)) takes over
<print(3) is running, n is 3, continues executing in [4]>
print (3) enters the for loop, prints "123\n" and returns
now the function that called print(3) (that is, main()) takes over
<main() is running>
main executes return(0) and exits
这是打印到控制台的内容:
1
12
123
如果您搬家print(n-1)
后,printf("\n")
您将拥有:
123
12
1