DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Program for finding the sum of the digits of a given number in .NET

By Ashok Nalam on 30 Dec 2012 | Category: C# | Tagged: number 
In this snippets we will see how to find the sum of digits of a given number.
  Discuss Add Comment   |  
Add rating Rate this resource   

In this program we will see how to sum the digits of a given number. 

E.g: If user enters number as 1234 then the output will be 1+2+3+4=9.

Program:

    class SumOfDigitsProgram
    {
        public static void Main()
        {
            int sum = 0;
            Console.WriteLine(" /********** Program to sum of Digits ************/");
            Console.Write("Enter a number:");
            int number = int.Parse(Console.ReadLine());
            int tempnumber = number;
            while (tempnumber > 0)
            {
                sum += (tempnumber % 10); // adds last digit of tempnumber to sum
                tempnumber /= 10; // divides tempnumber by 10 to cuts the last digit
            }
            Console.Write("Sum of {0} digit is {1}",number,sum);
            Console.Read();
        }
    }

Output:


Note: If you want to give number beyond the int range, change the  data type of input value(number).

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 8666  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.