C# How To Calculate the Sum of Digits
Sum of Digits
Add up all the digits of a number by taking one digit at a time:
Example
int number = 1234;
int sum = 0;
while (number > 0)
{
sum += number % 10;
number /= 10;
}
Console.WriteLine("Sum of digits: " + sum);
Explanation:number % 10 gives the last digit, which is added to sum.number /= 10 removes the last digit. 1 + 2 + 3 + 4 is 10.
Related Pages
C# Assignment Operators Tutorial