HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Recursion refers to the definition of the function method used in the function itself.
for example:
There was once a mountain, the mountain there was a temple, the temple has an old monk, was telling stories to young monk it! What story is it? "There was once a mountain, the mountain there was a temple, the temple has an old monk, was telling stories to young monk it! What story is it? 'There was once a mountain, the mountain there was a temple, the temple has an old monk, is a story to the young monk it! What story is it? /en/en/en ''
Syntax is as follows:
void recursion() { recursion(); /* 函数调用自身 */ } int main() { recursion(); }
C language support recursion, that is, a function can call itself. However, when using recursion, the programmer should be noted that the definition of a function exits from the conditions, otherwise it will go into an infinite loop.
Recursive function in solving many mathematical problems played a crucial role, such as the calculation of the factorial of a number, generate Fibonacci number, and so on.
The following example uses a recursive function to calculate the factorial of a given number:
#include <stdio.h> double factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 15; printf("%d 的阶乘为 %f\n", i, factorial(i)); return 0; }
When the above code is compiled and executed, it produces the following results:
15 的阶乘为 1307674368000.000000
Fibonacci The following example uses a recursive function to generate a given number of columns:
#include <stdio.h> int fibonaci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonaci(i-1) + fibonaci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%d\t%n", fibonaci(i)); } return 0; }
When the above code is compiled and executed, it produces the following results:
0 1 1 2 3 5 8 13 21 34