thought: Call itself directly or indirectly to perform the next calculation.
A general implementation process: a function or sub-process, either directly or indirectly, by invoking a function or subroutine to perform the calculation.
Requirements: Each time the loop is called, the size of the solution problem must be reduced. Adjacent two loop calls have to be closely linked, usually the previous invocation result is the input of the last call. There must be an exit, which is the recursive loop end condition.
Note: Recursive invocation of the algorithm is usually less efficient, and too many calls can cause stack overflow.
Example: Finding factorial
#include <stdio.h>int fact (int n); void main () {int i; printf ("Input:"); scanf ("%d", &i); printf ("The factorial result of%d is:%d", i,fact (i)); Getch ();} int fact (int n) {if (n<=1) return 1; Else return fact (n-1) *n;}
Analysis: Recursive algorithm thought is not difficult, simply said: is repeated call itself to solve the problem. But the timing of choosing recursion is very important, and some complex problems can be solved simply by recursion. This requires careful analysis.
Run Process: When the program runs toprintf ("The factorial result of%d:%d", i,fact (i)) begins to invoke the function fact (i). In the function fact (), n=i; determine whether n is less than or equal to 1 (this is important, is the condition of the end of recursion), is less than the return 1, otherwise returns the fact (n-1) *n, that is, the function of the call again the fact (), and the function of the parameters of 1, This satisfies the recursive principle that each invocation of the problem scale must be reduced. Once again the call is then judged, then called, and then judged, until n is less than or equal to 1. At this point, the return value of the function becomes larger and greater until the result is reached by recursive calls of several times.
Getting started with algorithms-recursion