Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the sum of digits of a number using recursion in C#?
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
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
Advertisements