next up previous contents
Next: 除錯器 gdb Up: 其他 Previous: 錯誤處理   Contents

遞迴

  1. 函式呼叫自己本身如:
    void recursion()
    {
       recursion(); /* function calls itself */
    }
    
    int main()
    {
       recursion();
    }
    
  2. 遞迴必須謹慎使用,最常舉的遞迴例子為階層運算:
    #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;
    }
    


2015-01-16