Find Sum of Digits in C#

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
Number manipulation

What you’ll learn

  • How to extract digits with % 10 and / 10.
  • The accumulator pattern: sum += digit.
  • Handling zero and negative numbers safely in C#.
  • Why complexity is linear in the number of digits.

Overview

Digit sum means adding every decimal digit of a number. For 12345, the result is 1 + 2 + 3 + 4 + 5 = 15. This is a core building block for Harshad numbers, digital roots, and many interview problems.

Two C# programs

Fixed number and user-input versions.

Live preview

Type values like 12345 or -802.

Modulo loop

Classic O(d) approach with constant extra space.

Prerequisites

while loops, integer division, modulo operator, and basic console I/O.

  • You understand that n % 10 gives the last digit and n / 10 removes it.
  • You can read integers with Console.ReadLine() and int.TryParse.

Understanding the concept of sum of digits

Sum of digits breaks a number into individual decimal digits and adds them together.

For 12345: digits are 1, 2, 3, 4, 5 and their sum is 15. For 0, the sum is 0.

Modulo and division pattern

Each step: digit = n % 10, then n = n / 10. Repeat until n becomes 0.

Example trace for 12345

5 + 4 + 3 + 2 + 1 = 15 — five loop iterations, one per digit.

Live preview

Enter an integer and see its digits and their sum.

Works for negatives by using absolute value.

Live result
Press “Compute sum”.

Algorithm

Goal: compute the sum of all decimal digits of n.

Normalize sign

Use Math.Abs(n) so negatives are handled like positives.

Extract digits

In a while (n > 0) loop, take n % 10 and set n /= 10.

Accumulate

Add each digit to sum and return the total.

📜 Pseudocode

Pseudocode
function sumOfDigits(n):
    n = abs(n)
    sum = 0
    while n > 0:
        sum = sum + (n mod 10)
        n = floor(n / 10)
    return sum
1

Sum of digits (fixed number)

Reference program: finds the digit sum of 12345 using a while loop.

c#
using System;

class Program
{
    static int SumOfDigits(int number)
    {
        number = Math.Abs(number);
        int sum = 0;

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

        return sum;
    }

    static void Main()
    {
        int number = 12345;
        int result = SumOfDigits(number);

        Console.WriteLine($"The sum of digits of {number} is: {result}");
    }
}
2

Sum of digits (user input)

Reads an integer from the console and prints its digit sum — useful for interview I/O practice.

c#
using System;

class Program
{
    static int SumOfDigits(int number)
    {
        number = Math.Abs(number);
        int sum = 0;

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

        return sum;
    }

    static void Main()
    {
        Console.Write("Enter an integer: ");

        if (!int.TryParse(Console.ReadLine(), out int number))
        {
            Console.WriteLine("Invalid input.");
            return;
        }

        Console.WriteLine($"Sum of digits: {SumOfDigits(number)}");
    }
}

Optimization and alternatives

Modulo loop. Best for interviews: O(d) time and O(1) extra space.

String approach. Convert to string and sum each char digit — readable, but uses extra memory.

Digital root. Repeat digit sum until one digit remains for follow-up problems.

❓ FAQ

Use a loop: add n % 10 to sum, then set n = n / 10. Repeat until n becomes 0.
0. The loop does not run and the sum stays 0.
Take Math.Abs(n) first, then apply the same digit-extraction loop.
Yes. Convert to string and add each char digit, but interviews often expect the modulo loop.
O(d), where d is the number of digits in n.
A Harshad number is divisible by the sum of its digits — digit sum is the building block.

🔄 Input / output examples

InputDigit sum
1234515
00
-80210

Edge cases and pitfalls

These cases are commonly tested in interviews.

n = 0

Return zero

The loop never runs; digit sum is 0.

Negative

Ignore sign

Use Math.Abs before extracting digits.

int.MinValue

Overflow edge case

Math.Abs(int.MinValue) overflows in C#. Cast to long for extreme values.

⏱️ Time and space complexity

TaskTimeExtra space
Sum digits of one numberO(d) (d = number of digits)O(1)

Summary

  • Core loop: sum += n % 10, then n /= 10.
  • Sign handling: use Math.Abs for negative inputs.
  • Complexity: linear in the number of digits.
Did you know?

Repeatedly summing digits until one digit remains is called finding the digital root.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful