C#
programming
sum of digits
algorithms
coding tutorial

Sum of digits in C

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Summing the digits of a number is a small problem, but it is a good exercise in integer arithmetic, loops, and input handling. In C#, the standard solution is to peel off digits with modulus and integer division until the number is exhausted.

The Arithmetic Approach

For a number like 472, the last digit is 472 % 10, which gives 2. Then 472 / 10 gives 47, and you repeat the process until the value becomes zero.

This leads to a compact implementation:

csharp
1using System;
2
3static int SumDigits(int number)
4{
5    number = Math.Abs(number);
6    int sum = 0;
7
8    while (number > 0)
9    {
10        sum += number % 10;
11        number /= 10;
12    }
13
14    return sum;
15}
16
17Console.WriteLine(SumDigits(472));
18Console.WriteLine(SumDigits(-903));

This is usually the best answer because it is efficient, does not allocate strings, and works directly with the numeric representation.

Handle Zero and Negative Values Correctly

One subtle point is 0. The loop above returns 0, which is correct, but only because the initial sum starts at zero. Negative numbers need normalization with Math.Abs, otherwise the modulus results can be harder to reason about.

If you want to make the behavior explicit:

csharp
1using System;
2
3static int SumDigits(int number)
4{
5    if (number == 0)
6    {
7        return 0;
8    }
9
10    number = Math.Abs(number);
11    int sum = 0;
12
13    while (number != 0)
14    {
15        sum += number % 10;
16        number /= 10;
17    }
18
19    return sum;
20}

That version reads clearly when edge-case behavior matters.

A String-Based Alternative

If readability matters more than raw efficiency, converting the number to a string is also valid:

csharp
1using System;
2using System.Linq;
3
4static int SumDigitsWithString(int number)
5{
6    return Math.Abs(number)
7        .ToString()
8        .Sum(ch => ch - '0');
9}
10
11Console.WriteLine(SumDigitsWithString(472));

This is easy to understand, but it creates a string and iterates over characters, so it does more work than the arithmetic version.

For interview questions or tight loops, prefer the arithmetic solution. For quick application code, either version may be fine.

Recursive Version

You can also write the logic recursively:

csharp
1using System;
2
3static int SumDigitsRecursive(int number)
4{
5    number = Math.Abs(number);
6
7    if (number < 10)
8    {
9        return number;
10    }
11
12    return (number % 10) + SumDigitsRecursive(number / 10);
13}
14
15Console.WriteLine(SumDigitsRecursive(472));

This is elegant for small examples, but iteration is usually the better default in C# because it avoids stack growth and keeps control flow straightforward.

When This Pattern Is Useful

The same digit-peeling technique appears in several related tasks:

  • checking whether a number is a palindrome
  • computing a digital root
  • counting digits
  • validating checksum-like logic in simple exercises

Once you understand % 10 and / 10, many introductory number-manipulation problems become easier.

Common Pitfalls

The most common mistake is forgetting to update the number inside the loop. If you never divide by 10, the loop never ends.

Another issue is mishandling negative values. If you do not normalize the sign first, the intermediate digits may be negative, which changes the sum.

Developers also sometimes reach for string conversion by default without realizing the arithmetic version is simpler and more direct for this exact problem.

Finally, if you are using the recursive approach, remember that it is mainly for clarity or teaching. For ordinary production code, the iterative loop is usually better.

Summary

  • The standard C# solution uses % 10 to extract digits and / 10 to remove them.
  • Normalize negative numbers with Math.Abs.
  • The iterative version is usually the clearest and most efficient.
  • A string-based version is readable but allocates more.
  • The same technique applies to many other digit-processing problems.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.