Write a program to recursively sum the individual digits to obtain a single digit using C#

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 379
Let's say, we have a number as N=123456789

If we sum them the result will be 1+2+3+4+5+6+7+8+9 =45 . If we further sum them it will be 4+5 = 9, which is a single digit.

How can we do so? The below is the program that will help us

using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(FindSingleDigit(123456789));
Console.ReadKey();
}

public static int FindSingleDigit(int N)
{
var sum = 0;
while (N != 0)
{
sum = sum + (N % 10);
N = N / 10;
}
return sum >= 10 ? FindSingleDigit(sum) : sum;
}
}
}


Let us understand the program first

while (N != 0)
{
sum = sum + (N % 10);
N = N / 10;
}


The loop continues till the value of "N" becomes zero and it gives the total sum of the individual digits. Then it comes out of the loop. Next we perform a checking if the sum obtained is greater than or equals to 10 which is a two digit. In that case , then program makes a recursive call. If it is a single digit, then that value gets return.

Let us analyze the program with an example.

Pass 1: sum = 45
Pass 2: sum = 9

Comments or Responses

Login to post response