
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
Find the Sum of Digits Using Recursion in C#
Let’s say we have set the number for which we will find the sum of digits −
int val = 789; Console.WriteLine("Number:",val);
The following will find the sum of digits by entering the number and checking it recursively −
public int addFunc(int val) { if (val != 0) { return (val % 10 + addFunc(val / 10)); } else { return 0; } }
Example
The following is our code to find the sum of digits of a number using Recursion in C#.
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:",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; } } } }
Output
Number: 789 Sum of Digits in 789 = 24
Advertisements