C language introduction tutorial — 11 recursion

Recursion just means that the function calls itself. When using recursion, however, the programmer needs to be careful to define an exit condition from the function, otherwise it will enter an infinite loop.

Example: 5! This is the factorial of 5, which is 5x4x3x2x1

#include<stdio.h>
int F(int a) / / factorial
{
if(a==1) return 1; // This is the exit
else return a*F(a- 1); // If it is not 1, return a*a-1 factorial
}

int main(a)
{
	int b = F(5);
	printf("%d\n",b);
	return 0;
}
Copy the code

Running results:

That’s recursion. Clever recursion can do a lot of things.

1 1 2 3 5 8 13? Let’s do this recursively, okay? The Numbers.

Solution:

if(a==1 || a==2) return 1; // This is the exit
else return F(a2 -)+F(a- 1); // Start with the third and add the first two
Copy the code

// You can try to write the complete program, and slowly absorb, digest.