C# program to find the sum of digits of a number using recursion
Here's a C# program that finds the sum of digits of a number using recursion:
using System;
class Program
{
static void Main()
{
int number = 12345;
int sumOfDigits = CalculateSumOfDigits(number);
Console.WriteLine("Sum of digits of " + number + " is: " + sumOfDigits);
}
static int CalculateSumOfDigits(int number)
{
// Base case: if the number is less than 10, return the number itself
if (number < 10)
{
return number;
}
else
{
// Recursive case: calculate the sum of the last digit (number % 10)
// and the sum of digits of the remaining digits (number / 10)
return (number % 10) + CalculateSumOfDigits(number / 10);
}
}
}
In this program, we have the CalculateSumOfDigits method that takes an integer number as input and returns the sum of its digits.
We have a base case where if the number is less than 10, we directly return the number itself, as the sum of digits of a single-digit number is the number itself.
In the recursive case, we calculate the sum of digits by adding the last digit of number (obtained by number % 10) with the sum of digits of the remaining digits (obtained by number / 10). We make a recursive call to CalculateSumOfDigits with the value (number / 10).
The recursive calls continue until we reach the base case (number is less than 10), at which point the recursion stops and the sum of digits is calculated.
In the example above, the output would be:
Sum of digits of 12345 is: 15
The sum of digits of the number 12345 is calculated as 1 + 2 + 3 + 4 + 5, which equals 15.