Home »
.Net »
C# Programs
C# | Sum of all digits of a number using recursion
Here, we are going to learn how to calculate the sum of all digits of a number using recursion in C#?
Submitted by Nidhi, on September 03, 2020 [Last updated : March 19, 2023]
Here we will input an integer number and then calculate the sum of all digits using the recursive method.
C# program to calculate the sum of all digits of a number using recursion
The source code to calculate the sum of all digits of a number using recursion is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to calculate the sum of all digits
//of a number using recursion
using System;
class Sample
{
public static int SumOfDigit(int number)
{
if (number == 0)
{
return 0;
}
else
{
int rem = 0;
rem = number % 10;
return (rem + sumOfDigit(number / 10));
}
}
public static void Main()
{
int num = 0;
int sum = 0;
Console.Write("Enter the number: ");
num = int.Parse(Console.ReadLine());
sum=SumOfDigit(num);
Console.WriteLine("Sum of digits: " + sum);
}
}
Output
Enter the number: 342
Sum of digits: 9
Press any key to continue . . .
Explanation
In the above program, we created a Sample class that contains two static methods SumOfDigits() and Main() method. In the Main() method, we declared an integer variable num and read the value of variable num, and then find the sum of all digits of the input number and print on the console screen.
Here, the method SumOfDigits() is a recursive method. Here we find the last digit of the number in every recursive call by finding the remainder, and then divide the number by 10 in every recursive call till the number is greater than 0.
C# Basic Programs »