Example analysis of recursive thought in C language

  • 2020-04-02 02:45:45
  • OfStack

This paper analyzes the recursive thought of C language, and shares it with you for your reference. Specific methods are as follows:

In layman's terms, recursion is calling itself.

The first difficulty with recursion is that Understand the recursive execution calls And the other is Set a reasonable recursive end condition .

Here's a simple program from the book:


#include <STDIO.H>
long fact(int n);
long rfact(int n);
int main(void)
{
 int num;
 printf("This program calculates factorials.n");
 printf("Enter a value in the range 0-12 (q to quit):n");
 while(scanf("%d",&num)==1)
 {
 if(num<0)
  printf("No negative numbers,please.n");
 else if (num>12)
 {
  printf("Keep input under 13.n");
 }
 else
 {
  printf("loop:%d factorial=%dn",num,fact(num));
  printf("recursion:%d factorial=%dn",num,rfact(num));
 }
 }
}

long fact(int n)
{
 long ans;
 for (ans=1;n>1;n--)
 {
 ans*=n;
 }
 return ans;
}

long rfact(int n)
{
 long ans;
 if (n>0)
 {
 ans=n*rfact(n-1);
 } 
 else
 {
 ans=1;
 }
 return ans;
}

The program is used to calculate the factorial, respectively by loop and recursive implementation. Let's describe the execution of recursion in words.
Let's say I calculate 5 factorial. N is equal to 5, so we call ourselves 4 times, so n is equal to 4, 3, 2,1. So when n is equal to 0, ans=1, rfact has just been executed completely, ans=1,

The stack is complete. Start the stack.

N times ans 5 times, so ans is equal to 1,2,6,24,120 times 24 times 5.

The 5! = 120

So let's see what happens to n :

N =5,4,3,2,1,

When we push, n is 1,2,3,4,5

Recursion is essentially a stack .

It is often easy to ignore the recursive condition is not satisfied, the function transferred control to the main function, the main function to continue to execute the rest of the statement this process, and cause confusion.

In fact, everything can explain things in life, like the four great classics are interlinked, each other can explain each other, do one thing that would not require even don't know the final result, but must understand what it is doing, understand it, but don't obsess to death, meditation a scholar.

Interested friends can test run this example to deepen understanding, I believe that the article described in the study of C programming has a certain reference value.


Related articles: