Recursive Method Call ใน C# เรียกว่า Recursion ตัวอย่างการคำนวณยกกำลังด้วย Recursion:
หากกำลัง (p) ไม่เท่ากับ 0 ให้เรียกฟังก์ชันซ้ำ (Recursion):
if (p != 0)
{
return (n * power(n, p - 1));
}
ตัวแปร n คือฐาน และ p ลดลงทีละ 1 ในแต่ละรอบ
ตัวอย่าง
using System;
using System.IO;
public class Demo
{
public static void Main(string[] args)
{
int n = 5;
int p = 2;
long res;
res = power(n, p);
Console.WriteLine(res);
}
static long power(int n, int p)
{
if (p != 0)
{
return (n * power(n, p - 1));
}
return 1;
}
}