การเรียกเมธอดแบบเรียกซ้ำใน C # เรียกว่าการเรียกซ้ำ เรามาดูตัวอย่างการคำนวณกำลังของตัวเลขโดยใช้การเรียกซ้ำ
ในที่นี้ หากกำลังไม่เท่ากับ 0 การเรียกใช้ฟังก์ชันจะเกิดขึ้นซึ่งในที่สุดเป็นการเรียกซ้ำ -
if (p!=0) {
return (n * power(n, p - 1));
} ด้านบน n คือตัวเลขและกำลังลดลงทุกครั้งที่ทำซ้ำดังแสดงด้านล่าง −
ตัวอย่าง
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;
}
}