คำนวณแฟกทอเรียล (Factorial) ด้วยฟังก์ชัน recursive checkFact()
ถ้าค่าเป็น 1 คืนค่า 1 (เพราะ 1! = 1):
if (n == 1) return 1;
ถ้าไม่ใช่ เรียกฟังก์ชันซ้ำ:
Iteration 1: 5 * checkFact(4) Iteration 2: 4 * checkFact(3) Iteration 3: 3 * checkFact(2) Iteration 4: 2 * checkFact(1)
ตัวอย่าง
using System;
namespace Demo {
class Factorial {
public int checkFact(int n) {
if (n == 1) return 1;
else return n * checkFact(n - 1);
}
static void Main(string[] args) {
int value = 9;
int ret;
Factorial fact = new Factorial();
ret = fact.checkFact(value);
Console.WriteLine("Value is : {0}", ret);
Console.ReadLine();
}
}
}
ผลลัพธ์
Value is : 362880