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

CsharpServer Side ProgrammingProgramming

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
raja
Published on 25-Jul-2018 10:20:36
Advertisements