Gọi phương thức đệ quy trong C# gọi là Đệ quy (Recursion). Ví dụ tính lũy thừa của số bằng đệ quy.
Nếu lũy thừa khác 0, hàm tự gọi lại - đó là đệ quy:
if (p != 0) {
return (n * power(n, p - 1));
}
Trong đó n là cơ số, p giảm dần mỗi lần gọi.
Ví dụ
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;
}
}