Preorder recursion and postorder recursion

Look at the following two programs and think about their output.

#include<stdio.h>
void test1(int n)
{
	if (n > 0)
	{
	    n--;
	    printf("%d ", n);
	    test1 (n);
	}
}

void test2(int n)
{
	if (n > 0)
	{
	    n--;
            test2 (n);
	    printf("%d ", n);
	}
}

intmain()
{
	int n = 6;
	test1 (n);
	printf("\n");
	test2 (n);
	printf("\n");
	return 0;
}
operation result:
Thinking: Why is the position of "printf" in the called function different, and the output results are so different?

The output results of test1 are output according to the program, and the results are consistent with the imagination; the output results of test2 are not what we thought before. 
Because test1 is pre-order recursion, the pre-order recursive code is sequential; test2 is post-order recursion, and the reverse-order recursive code is in reverse order.

Look at the program again and think about its output.

#include<stdio.h>
void test3(int n)
{
	int i;
	for (i = 0; i < n; i++)
	{
		printf("%d ", i);
	}
}

intmain()
{
	int n = 6;
	test3(n);
	printf("\n");
	return 0;
}

operation result:

This is the same as the output of test2, what does it mean?

Explain that in some cases, recursion can be replaced by loop, and loop can also be replaced by recursion.

Note:
Recursion is logically difficult to understand and makes the code less readable.
However, recursion can reverse the output by simply putting a preorder postorder.
If you use a loop, you have to change a lot. as follows:

#include<stdio.h>  
void test4(int n)  
{  
    int i;  
    for (i = n - 1; i>=0; i--)  
    {  
        printf("%d ", i);  
    }  
  
intmain()  
{       
    test4(n);  
    printf("\n");  
    return 0;  
}  
operation result:


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326793031&siteId=291194637