[Study Notes] [C Language] recursion, Study Notes Recursion
I. Basic Content:
Functions in C can be called recursively, that is, they can be called directly (simple recursion) or indirectly (indirect recursion) by themselves.
Key points:
1. c functions can be called recursively.
2. It can be called either directly or indirectly. Currently, we only discuss direct recursive calls.
Ii. Recursive Conditions
The recursive method must meet the following three conditions:
1. the problem to be solved can be transformed into a new problem, and the solution to this new problem is still the same as the original solution, only the processed objects increase or decrease regularly.
Note: The method for solving the problem is the same. The parameters for calling a function are different each time (with a regular increase or decrease). If there is no rule, recursive calls cannot be applied.
2. You can apply this conversion process to solve the problem.
Note: using other methods is troublesome or difficult to solve, while using recursive methods can solve the problem well.
3. There must be a clear condition for ending recursion.
Note: You must end recursive calls in appropriate places. Otherwise, the system may crash.
Iii. Code
1/* 2 design a function to calculate the Npower of B, 3 4 recursion, two conditions: 5 1. the function calls itself. 6. 2. there must be a clear return value 7 */8 # include <stdio. h> 9 int pow2 (int B, int n); 10 11 int main () 12 {13 int c = pow2 (3, 2 ); 14 15 printf ("% d \ n", c); 16 return 0; 17} 18 19/* 20 pow2 (B, 0) = 121 pow2 (B, 1) = B = pow2 (B, 0) * b22 pow2 (B, 2) = B * B = pow2 (B, 1) * b23 pow2 (B, 3) = B * B = pow2 (B, 2) * b24 25 1> n is 0, and the result must be 126 2> n> 0, pow2 (B, n) = pow2 (B, n-1) * b27 */28 29 int pow2 (int B, int n) 30 {31 if (n <= 0) return 1; 32 return pow2 (B, n-1) * B; 33} 34 35/* 36 int pow2 (int B, int n) 37 {38 // used to save the calculation result 39 int result = 1; 40 41 42 // result * = B; 43 // result * = B; 44 // result * = B; 45 // result * = B; 46 //.... 47 48 // n times 49 50 51 for (int I = 0; I <n; I ++) 52 {53 result * = B; 54} 55 56 return result; 57 }*/