C# program to find the sum of digits of a number using Recursion



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#.

Live Demo

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
Updated on: 2020-06-19T12:13:42+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements