12,747,448 members (38,077 online)
Rate this:
See more:
Program to find the sum of digits of a given number until the sum becomes a single digit. (e.g. 12345=>1+2+3+4+5=15=>1+5=6) .
Posted 21-Apr-13 1:50am
Updated 21-Feb-16 6:52am
Philippe Mori 22-Feb-16 22:00pm

Probably not what your teacher wants but surely the easier way to do it (assuming number >= 0).

`return a == 0 ? 0 : (a + 8) % 9 + 1;`

Rate this:

## Solution 1

This sounds like homework, so no code!
But this is really simple:
1) Create a "total" variable, and set a "working" variable to the value you want to sum.
2) Create a loop, and set the total variable to zero
3) In the loop, add the working variable modulo 10 to the total.
4) Divide the working variable by 10
5) If the working variable is greater than zero then go back round the loop at (3)
6) If the total variable is less than ten, you have the value.
7) Otherwise, set the working variable to the total variable, and go back round the loop at (2)
0x01AA 21-Feb-16 13:20pm

A 5 for your help anyway.
OriginalGriff 21-Feb-16 14:46pm

Are you rerunning "the best of OriginalGriff"? :laugh:
Rate this:

## Solution 2

```class Program
{
static void Main(string[] args)
{
int sum = DigitSum(Convert.ToInt32(num));
Console.WriteLine("sum:{0}", sum);
}
static private int DigitSum(int num)
{
int sum = 0;
while (num > 0)
{
sum += num % 10;
num /= 10;
}
if (sum > 9)
{
sum = DigitSum(sum);
}
return sum;
}
}
```
Dave Kreskowiak 21-Feb-16 13:20pm

Do NOT do peoples homework for them! You're not actually helping them and chances are really good they're going to fail the class if they turn in YOUR work and not theirs.
Andreas Gieriet 21-Feb-16 15:43pm

C'mon! If he fails, he deserves it!
He got the chance to learn from template - it's up to him to make the best from it. No reason to down-vote.
Cheers
Andi
PS: This post was from two years ago! Why the heck does it re-appear so high up?
Dave Kreskowiak 21-Feb-16 15:51pm

Probably because someone posted spam to it. That'll resurrect it and put it back to the top of the queue, even if the spam was them removed.

Top Experts
Last 24hrsThis month
 Graeme_Grant 250 OriginalGriff 130 Dave Kreskowiak 118 ppolymorphe 92 Maciej Los 85
 OriginalGriff 3,658 Peter Leow 2,761 ppolymorphe 2,023 Karthik Bangalore 1,740 Richard MacCutchan 1,329

Web02 | 2.8.170215.1 | Last Updated 21 Feb 2016