สมมติเรามีตัวเลขที่ต้องการหาผลรวมของหลักต่างๆ:
int val = 789;
ใช้ฟังก์ชัน Recursive เพื่อคำนวณผลรวม:
public int addFunc(int val) {
if (val != 0) {
return (val % 10 + addFunc(val / 10));
} else {
return 0;
}
}
ตัวอย่างโค้ดเต็ม
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
int val, result;
Calc cal = new Calc();
val = 789;
Console.WriteLine("Number: {0}", val);
result = cal.addFunc(val);
Console.WriteLine("Sum of Digits in {0} = {1}", val, result);
Console.ReadLine();
}
}
class Calc {
public int addFunc(int val) {
if (val != 0) {
return (val % 10 + addFunc(val / 10));
} else {
return 0;
}
}
}
}
ผลลัพธ์
Number: 789 Sum of Digits in 789 = 24
คำอธิบาย: 7 + 8 + 9 = 24 ฟังก์ชันจะเรียกตัวเองซ้ำๆ โดยนำเลขหลักสุดท้าย (val % 10) มาบวกกับผลลัพธ์ของการเรียกฟังก์ชันต่อไปด้วยค่า val / 10 จนกว่าจะเหลือ 0