Click here to Skip to main content
11,495,371 members (53,681 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
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
Rate this: bad
good
Please Sign up or sign in to vote.

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)
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

class Program
    {
        static void Main(string[] args)
        {
            string num = Console.ReadLine();
            int sum = DigitSum(Convert.ToInt32(num));
            Console.WriteLine("sum:{0}", sum);
            Console.Read();
        }
        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;
        }
    }
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Dnyaneshwar@Pune 692
1 CHill60 318
2 Sascha Lefèvre 275
3 Sergey Alexandrovich Kryukov 255
4 Nakul Chaudhari 236
0 Sergey Alexandrovich Kryukov 10,307
1 OriginalGriff 8,821
2 Sascha Lefèvre 3,889
3 Maciej Los 3,412
4 Richard Deeming 2,560


Advertise | Privacy | Mobile
Web02 | 2.8.150520.1 | Last Updated 21 Apr 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100