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

CsharpProgrammingServer Side Programming

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
raja
Published on 21-Aug-2018 09:01:40
Advertisements