next up previous contents
Next: 實機練習題 Up: 函式 Previous: 變數生命週期   Contents   DYWANG_HOME

遞迴

  1. 函式呼叫自己本身如:
    void recursion() {
       recursion();
    }
    
    int main(){
       recursion();
    }
    
  2. 遞迴必須謹慎使用,最常舉的遞迴例子為階層運算:
    [dywang@dyw219 zzz]$ vim function8.c
    [dywang@dyw219 zzz]$ cat function8.c
    #include <stdio.h>
    
    int factorial(unsigned int i) {
       if(i <= 1) return 1;
    
       return i * factorial(i-1);
    }
    int  main() {
    	int i = 15;
    	printf("Factorial of %d is %d\n", i, factorial(i));
    	return 0;
    }
    
  3. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o function8 function8.c
    
  4. 執行結果
    [dywang@dyw219 zzz]$ ./function8
    Factorial of 15 is 2004310016
    



2020-01-02