Condense a Number (Digital Root) in C#

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digit manipulation

What you’ll learn

  • How repeated digit sums shrink a number down to one digit—that single digit is the digital root (“condensed” value).
  • An iterative C# program like the classic tutorial, plus a one-line mod 9 trick for nonnegative inputs.
  • A live preview, plain-language tie-in with divisibility by 9, and pitfalls such as 0 and multiples of 9.

Overview

Picture a whole number written in ordinary decimal form. Add its digits. If the answer is still two digits or more, add again. Stop when you reach exactly one digit. That final value is what many puzzles call the “condensed” number; mathematicians call it the digital root. Classic homework example: 9875 → 29 → 11 → 2.

Two programs

First: nested loops that mirror how you would do it by hand. Second: a short formula using % 9 when n fits in long.

Live preview

Type a nonnegative integer and see the digital root without compiling.

Terminology

“Condense” here is not deleting random digits; it is this repeatable sum recipe.

Prerequisites

Decimal digits, remainder % 10, integer division / 10, and nested while loops.

  • using System;, class Program, static void Main(), Console.WriteLine.
  • long for the second demo when you want a wide literal without iteration.

Digital root vs digit sum

The digit sum of 9875 is 9+8+7+5 = 29. That answer still has two digits. The digital root keeps going: 29 → 11 → 2.

Same operations as the original tutorial; we just name the final digit properly so you do not confuse one addition pass with the finished task.

One pass digit sum
Repeat digital root
mod 9 shortcut

Why 9 shows up

Ten is one more than nine. That simple fact means replacing a number by the sum of its decimal digits does not change its remainder modulo 9. After enough rounds you land on the single digit that matches that remainder pattern (with 9 standing in when the remainder would look like 0 but the original number was positive).

9875

9875 divided by 9 leaves remainder 2, and the slow digit-sum path also ends at 2.

Quick patterns

18 Root 9
Steps
1 + 8 = 9
49 Root 4
Steps
4 + 9 = 13, then 1 + 3 = 4

Tip: multiples of 9 (except zero itself mid-chain) want to collapse to 9, not 0, when you use the shortcut formula for positive inputs.

Live preview

Nonnegative integers inside JavaScript’s safe range. Uses the same repeat-until-one-digit rule as Example 1.

Negative numbers are not accepted here so the widget matches the sample programs.

Live result
Press “Condense” to see each digit-sum round (e.g. 9 + 8 + 7 + 5 = 29, then keep going) until one digit remains.

Algorithm (iterative)

Goal: turn a nonnegative integer into one decimal digit by repeating digit sums.

While the working value is larger than 9

Peel digits with % 10, drop them with / 10, add into a running total, then replace the working value by that total.

Finish

Return the last value (already between 0 and 9).

📜 Pseudocode

Pseudocode
function condense(n):  // n ≥ 0
    while n > 9:
        sum ← 0
        t ← n
        while t > 0:
            sum ← sum + (t mod 10)
            t ← floor(t / 10)
        n ← sum
    return n
1

Iterative condensation (reference flow)

Keeps a working copy n so the outer loop is easy to read. Assumes nonnegative input; number in Main stays unchanged for the print message.

c#
using System;

class Program
{
    static int CondenseNumber(int number)
    {
        int n = number;

        while (n > 9)
        {
            int sum = 0;
            int tmp = n;

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

            n = sum;
        }

        return n;
    }

    static void Main()
    {
        int number = 9875;
        int condensedNumber = CondenseNumber(number);

        Console.WriteLine($"The condensed form of {number} is: {condensedNumber}");
    }
}

Explanation

The inner loop tears apart tmp digit by digit; n becomes the next value to shrink. Because C# passes int by value, the variable number in Main is still 9875 when you print.

while (n > 9)

Stopping rule. Values 0 through 9 exit immediately; anything bigger gets another digit-sum round.

2

Closed form with long (mod 9)

Same math answer in one hop for nonnegative n. Handy when n is wide but still fits in long.

c#
using System;

class Program
{
    static int DigitalRootNonnegative(long n)
    {
        if (n == 0)
        {
            return 0;
        }

        int r = (int)(n % 9);
        return r == 0 ? 9 : r;
    }

    static void Main()
    {
        long a = 9875L;
        long b = 999999999999999999L;

        Console.WriteLine($"dr({a}) = {DigitalRootNonnegative(a)} (closed form)");
        Console.WriteLine($"dr({b}) = {DigitalRootNonnegative(b)} (closed form)");
    }
}

Explanation

Eighteen nines sum to a multiple of nine, so the digital root is 9. The ternary maps remainder 0 to output 9 for every positive multiple of nine.

return r == 0 ? 9 : r;

Guard already handled n == 0. After that, remainder 0 can only mean “nonzero multiple of 9,” whose digital root is 9.

Optimization

mod 9 shortcut. Use Example 2 when you trust the input range and want constant-time code.

Monster inputs as text. If n arrives as a string of digits, scan characters once per round or accumulate sum % 9 in one pass instead of building huge integers.

Interview: trace 9875, mention nonnegative inputs, then drop the formula.

❓ FAQ

Here it means the digital root: add the decimal digits, and if the answer still has more than one digit, repeat until you get a single digit from 0 to 9. Example: 9875 becomes 9+8+7+5 = 29, then 2+9 = 11, then 1+1 = 2.
No. One pass gives the ordinary digit sum (like 29 for 9875). Condensing keeps going until only one digit is left.
For n greater than 0: let r be n % 9. The digital root is 9 when r is 0, otherwise r. For n equal to 0, the digital root is 0. This works because 10 leaves remainder 1 when divided by 9, so the whole number and its digit sum match modulo 9.
Both use adding digits, but only the final single-digit answer is the digital root. Keeping that distinction clear helps on tests and in interviews.
The programs on this page assume nonnegative integers, like the original walkthrough. For negatives, agree on a rule first—often people use the absolute value—or reject the input.
The iterative version touches digits a few times; for normal int-sized homework values it is tiny. The closed form does one modulo and is O(1) time and O(1) extra space.

🔄 Input / output examples

Change the literal in Main or read from the console with long.Parse(Console.ReadLine()) when you want interactive tests.

InputDigital rootNotes
98752Walkthrough from the reference
00Both approaches agree
99Already one digit
1891 + 8

Edge cases and pitfalls

Feeding negatives into the iterative loop without a plan can loop forever or surprise you; stick to nonnegative inputs unless you normalize first.

Zero

n = 0

The outer loop never runs; digital root 0. The shortcut must check n == 0 before turning remainder 0 into 9.

Multiples of 9

n % 9 == 0, n > 0

Answer is 9, not 0. Mixing that up is the most common closed-form mistake.

Types

Wide literals

Use long (or larger) when you demo giant constants; int overflows sooner.

Other bases

Not universal

The mod 9 trick belongs to base ten. Binary or hexadecimal digit games need different reasoning.

⏱️ Time and space complexity

ApproachTimeExtra space
Iterative (int homework sizes)Few digit passes; feels instantO(1)
Iterative (big picture)Proportional to digit count times roundsO(1)
Closed formO(1)O(1)

If n is stored as a long string, each naive round costs time linear in the string length.

Summary

  • Idea: repeat digit sums until one digit remains—the digital root.
  • Code: nested loops, or n == 0 ? 0 : (n % 9 == 0 ? 9 : n % 9) for nonnegative n.
  • Watch-outs: do not confuse with a single digit-sum pass; handle 0, multiples of 9, and negatives deliberately.
Did you know?

In base ten, the digital root (this page’s “condensed” value) lines up with divisibility by 9: for n > 0, repeated digit sums end at 9 when n is a nonzero multiple of 9, otherwise they end at n % 9.

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.

8 people found this page helpful