1. recursion: The function calls itself
This is the simplest recursion, but it will always be executed and can be terminated by Ctrl + C.
# Include <stdio. h> void PRN (void) {printf ("C ++ builder 2009 \ n"); PRN ();/* Self-called; note that it will always be executed, use Ctrl + C to terminate the execution */} int main (void) {PRN (); getchar (); Return 0 ;}
2. Recursive expressions must have the following conditions:
# Include <stdio. h> void PRN (INT num) {printf ("% d \ n", num); If (Num> 0) PRN (-- num);} int main (void) {PRN (9); getchar (); Return 0 ;}
3. instance: Flip string
# Include <stdio. h> void revers (char * cs); int main (void) {revers ("123456789"); getchar (); Return 0;} void revers (char * cs) {If (* cs) {revers (Cs + 1); putchar (* cs );}}
4. instance: factorial
# Include <stdio. h> int factorial (INT num); int main (void) {int I; for (I = 1; I
5. instance: integer to binary
# Include <stdio. h> void inttobinary (unsigned num); int main (void) {inttobinary (255);/* 11111111 */getchar (); Return 0;} void inttobinary (unsigned num) {int I = num % 2; If (Num> 1) inttobinary (Num/2); putchar (I? '1': '0'); // putchar ('0' + I);/* can replace the above sentence */}
6. Analyze recursion:
# Include <stdio. h> void PRN (unsigned N); int main (void) {PRN (1); getchar (); Return 0;} void PRN (unsigned N) {printf ("% d: % P \ n", N, & N);/* a */If (n
Output in this example:
Analysis:
ProgramRun to A and output the first line.
N = 1 at this time.
... Such a loop can be executed until n = 4, A, but B cannot be executed because it does not meet the condition. C can finally be executed when n = 4.
However, at this time, four functions in the memory are waiting for return (when n = 1, 2, 3, and 4). Let's call them F1, F2, F3, and F4.
F4 executes C and outputs the fifth line. The function returns the result to F3 (n = 3 at this time). F3 can continue to execute C and output the sixth line.
F3-> F2-> continue C, output the seventh line.
F2-> F1-> continue C. The eighth line is output. The execution is complete!
In this case, recursive functions are still very memory-intensive (Sometimes it is better to use loops directly), but they are indeed clever.