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

 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

Updated on: 22-Jun-2020

378 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements