This was one of the first exercises we received during my first year of programming. I was asked about it in an interview years ago and I also found it as a programming challenge in a website. For a given number, for example 723, find the sum of its digits. In our example is 7+2+3 which is 12. To my surprise, not everyone is able to find an elegant solution. I saw many trying to convert it to string and then loop though the characters etc. Here we will provide an elegant solution based on math and how integer division is working in most programming languages, including C#.

public static long DigitsSum(long num)
{
    long sum = 0;

    while (num > 0)
    {
        sum += num % 10;
        num /= 10;
    }

    return sum;
}

What this code does is getting the modulo 10 of a number, which can be translated to the last digit from left to right, and adds it to the sum. In our example of 723, that would be the number 3. Then it divides the number by 10 and continues the same logic until the result of the division is 0. In our example, 723 mod 10 = 3, sum = 3, 723/10 = 72, then 72 mod 10 = 2 and new sum = 3+2 = 5, and lastly 72/10 = 7, 7 mod 10 = 7 and new sum = 5+7 = 12. 7/10 = 0 and this causes the loop to end and return the result which is 12.

Find the sum of the digits in a number – C# Method