# How to find the sum of digits of a number using recursion in C#?

CsharpProgrammingServer Side Programming

#### Complete Python Prime Pack

9 Courses     2 eBooks

#### Artificial Intelligence & Machine Learning Prime Pack

6 Courses     1 eBooks

#### Java Prime Pack

9 Courses     2 eBooks

To get the sum of digits using recursion, set a method in C# that calculates the sum.

static int sum(int n) {
if (n != 0) {
return (n % 10 + sum(n / 10));
} else {
return 0;
}

The above method returns the sum and checks it until the entered number is not equal to 0.

The recursive call returns the sum of digits o every recursive call −

return (n % 10 + sum(n / 10));

Let us see the complete code −

## Example

Live Demo

using System;
class Demo {
public static void Main(string[] args) {
int n, result;
n = 22;
Console.WriteLine("Number = {0}", n);
result = sum(n);
Console.WriteLine("Sum of digits = {0}", result);
}
static int sum(int n) {
if (n != 0) {
return (n % 10 + sum(n / 10));
} else {
return 0;
}
}
}

## Output

Number = 22
Sum of digits = 4
Updated on 22-Jun-2020 09:54:46