- คือการที่ฟังก์ชั่นเรียกใช้งานตัวมันเอง
- เรียนกใช้แบบทางตรง คือฟังก์ชั่นเรียกตัวของมันเอง
- เรียนกใช้แบบทางอ้อม คือมันเรียกใช้ฟังก์ชั่นอื่น และฟังก์ชั่นอื่นนั้นเรียกฟังก์ชั่นแรกอีกที
- ทุก recursion ฟังก์ชั่นต้องมีจุดสิ้นสุด ( base condition ) ที่มันจะไม่เรียกตัวมันเอง
- ไม่ควรใช้ recursion กับโค๊ดที่มีการเรียกตัวมันเองหลายชั้น
- แต่ละครั้งที่ฟังก์ชั่นถูกเรียก มันจะสร้างพื้นที่ของมันเอง
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int fact(int n); | |
int main(void) | |
{ | |
// Factorial | |
// 3! = 3 x 2 x 1 | |
// 5! = 5 x 4 x 3 x 2 x 1 | |
int ans; | |
ans = fact(5); | |
printf("%d",ans); | |
return 0; | |
} | |
int fact(int n) | |
{ | |
if( n == 1 ) | |
{ | |
return 1; | |
} | |
return n * fact(n-1); | |
} |