DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Sum of digits of a number in .NET using for loop

By Ashok Nalam on 17 Jul 2013 | Category: C# | Tagged: .NET number 
In this program we will see how to sum the digits of a given number using for loop.
  Discuss Add Comment   |  
Add rating Rate this resource   

In this program we will see how to sum the digits of a given number using for loop

E.g: If user enters number as 123456 then the output will be 1+2+3+4+5+6=21

Program:

namespace DotNetMirror
{
    class SumofDigitsUsingForLoop
    {
        public static void Main()
        {
            int sum = 0;
            Console.WriteLine(" /********** Program to sum of digits using for loop ************/");
            Console.Write("Enter a number:");
            int number = int.Parse(Console.ReadLine()); int tempNumber = number ;
            for (; number != 0; number = number / 10)
            {
                sum += (number % 10);
            }
            Console.Write("Sum of {0} digit is {1}", tempNumber, sum);
            Console.Read();
        }
    }
}   

Output:

 /********** Program to sum of digits using for loop ************/
Enter a number:123456
Sum of 12346 digit is 21

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) : 9226  (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.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys