Condense a Number (Digital Root) in C

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digit manipulation

What You’ll Learn

Condensing a number means repeatedly summing digits until one digit remains — the digital root. This tutorial covers iterative reduction, the mod-9 shortcut, a live preview, worked C examples, edge cases, and complexity.

Digital Root

One digit

Repeat digit sum until the value is in 0…9.

vs Digit Sum

One pass

Digit sum is one step; condensing may need several.

Iterative

% 10 / 10

Extract digits in a loop until n ≤ 9.

Mod 9

O(1)

Closed form for nonnegative n using congruence mod 9.

Live Preview

Try any n

Enter a nonnegative integer and see its digital root.

Edge Cases

0 & ×9

Handle 0 and multiples of 9 carefully in the formula.

Introduction

Condensing a number (finding its digital root) means summing decimal digits repeatedly until only one digit remains. Classic chain: 9875 → 29 → 11 → 2.

A one-time digit sum may still be multi-digit. Condensing continues until the value is in 0…9. In base 10, a closed-form shortcut uses congruence modulo 9.

Why it matters?

It trains digit extraction, loop design, and a classic modular-arithmetic interview shortcut.

Key Highlights

Repeat Until One Digit

Keep summing until n ≤ 9.

Mod 9 Shortcut

Same answer for nonnegative n in O(1).

Multiples of 9

Positive multiples map to root 9, not 0.

Zero Special Case

Digital root of 0 is 0.

In short: sum digits until one remains — or use n % 9 (with the 0 / multiples-of-9 fixes).

📝 Problem & Approach

Given a nonnegative integer n, return its digital root (single digit after repeated digit sums).

c
// 9875 → 9+8+7+5 = 29 → 2+9 = 11 → 1+1 = 2

Inputs & Outputs

ItemTypeDescription
nintNonnegative integer to condense (define policy for negatives).
Return / printintSingle digit in 0…9 — the digital root.

Minimal workflow

Pseudocode
function condense(n):
    while n > 9:
        s = 0
        while n > 0:
            s += n % 10
            n /= 10
        n = s
    return n

Method comparison

MethodIdeaNotes
IterativeRepeat digit sum until n ≤ 9Best for showing the process
Closed formn % 9 with 0 / ×9 fixesO(1) for nonnegative ints
Show chainRecord each reduction stepGreat interview explanation

⚡ Quick Reference

GoalPattern
Extract last digitn % 10
Drop last digitn /= 10
Outer loopwhile (n > 9)
Closed formn % 9 == 0 ? 9 : n % 9 (n > 0)
Alt formula1 + (n - 1) % 9 for n > 0
Classic check9875 → 2

📋 Digit Sum vs Digital Root vs Mod 9

Same family of ideas — different stopping rules and speed.

Digit sum
one pass

9875 → 29 only — may still be multi-digit

Digital root
repeat

9875 → 29 → 11 → 2 — final single digit

Mod 9
O(1)

Same root via congruence; watch 0 and ×9

Interview tip
loops first

Show iterative method, then derive the shortcut

Context

When This Problem Shows Up

Reach for digital-root drills when digit loops and mod-9 shortcuts matter.

  1. Interview warm-ups

    Checks % / // digit extraction and whether you know the mod-9 trick.

  2. Teaching base-10 congruence

    Makes “n ≡ digit sum (mod 9)” concrete.

  3. Checksum / divisibility by 9

    Digital root 9 means the number is divisible by 9 (if n > 0).

  4. Huge-number follow-ups

    Process digit strings when values exceed fixed integer widths.

  5. Not a one-pass digit sum

    If the prompt stops after one sum, that is a different problem.

Key benefit: one short problem that covers digit loops, edge cases, and a clean O(1) modular shortcut.

🔮 Live Preview

Enter a nonnegative integer and get its digital root.

Nonnegative integers only (preview limited to JS safe integers).

Live result
Press "Condense" to see the digital root.

Examples Gallery

Three complete C programs — iterative reduction, mod-9 closed form, and a reduction-chain display. Click View Output to reveal sample console results.

📚 Getting Started

Reference-style loops — keep reducing until one digit remains.

Example 1 — Iterative Condensation

Outer loop until n ≤ 9; inner loop sums digits with % 10 and /= 10.

c
#include <stdio.h>

int condenseNumber(int number) {
    int n = number;
    while (n > 9) {
        int digitSum = 0;
        while (n > 0) {
            digitSum += n % 10;
            n /= 10;
        }
        n = digitSum;
    }
    return n;
}

int main(void) {
    int number = 9875;
    printf("The condensed form of %d is: %d\n", number, condenseNumber(number));
    return 0;
}

How It Works

The inner loop accumulates digits into digitSum; the outer loop assigns that sum back to n until the value is within 0…9.

⚡ Closed Form

Same answer for nonnegative inputs in O(1) time.

Example 2 — Closed Form Using Mod 9

Special-case 0; for positives divisible by 9 return 9 instead of 0.

c
#include <stdio.h>

int digitalRootNonnegative(long long n) {
    int r;
    if (n == 0) {
        return 0;
    }
    r = (int)(n % 9);
    return r == 0 ? 9 : r;
}

int main(void) {
    printf("dr(9875) = %d (closed form)\n", digitalRootNonnegative(9875));
    printf("dr(999999999999999999) = %d (closed form)\n",
           digitalRootNonnegative(999999999999999999LL));
    return 0;
}

How It Works

In base 10, n and the sum of its digits are congruent mod 9. Mapping remainder 0 to 9 (when n > 0) matches the iterative digital root.

🔎 Show the Process

Print each reduction step for interviews and debugging.

Example 3 — Reduction Chain

Return the digital root and record every intermediate sum.

c
#include <stdio.h>

#define CHAIN_CAP 32

struct Result {
    int root;
    int chain[CHAIN_CAP];
    int chainLen;
};

struct Result condenseWithChain(int number) {
    struct Result result;
    int n = number;
    int digitSum;

    result.chainLen = 0;
    result.chain[result.chainLen++] = n;

    while (n > 9) {
        digitSum = 0;
        while (n > 0) {
            digitSum += n % 10;
            n /= 10;
        }
        n = digitSum;
        if (result.chainLen < CHAIN_CAP) {
            result.chain[result.chainLen++] = n;
        }
    }
    result.root = n;
    return result;
}

int main(void) {
    struct Result result = condenseWithChain(9875);
    int i;

    for (i = 0; i < result.chainLen; i++) {
        if (i > 0) {
            printf(" -> ");
        }
        printf("%d", result.chain[i]);
    }
    printf("\n");
    printf("Digital root: %d\n", result.root);
    printf("Also: 1 + (9875 - 1) %% 9 = %d\n", 1 + (9875 - 1) % 9);
    return 0;
}

How It Works

Same iterative logic, but each assignment to n is appended to chain. The alternate formula 1 + (n - 1) % 9 matches for positive n.

🧠 How the Algorithm Condenses

1

Start with n

If already ≤ 9, you are done.

Check
2

Sum digits

Peel digits with % 10 / / 10 into a running total.

Reduce
3

Assign and repeat

Set n to that sum; continue while n > 9.

Loop
=

Digital root

The final single digit — equivalently n % 9 with edge fixes.

🔎 Worked Walkthrough — 9875

Trace iterative digit sums until one digit remains.

StepCurrent nDigit sumNext
198759+8+7+5 = 2929
2292+9 = 1111
3111+1 = 22
Done2root = 2

Check: 9875 % 9 = 2 — matches the iterative chain.

Use Cases

Where digital-root / condense problems show up beyond the interview prompt.

1. Interview Warm-Ups

Digit loops plus an optional O(1) formula.

Example: write condenseNumber(n).

2. Teaching Mod 9

Shows why digit sums preserve remainder mod 9.

Example: chalkboard 9875 ≡ 2.

3. Divisibility by 9

Root 9 (n > 0) means n is divisible by 9.

Example: quick check for 18, 27, 36.

4. Numerology / puzzles

Many “reduce to one digit” puzzles are digital roots.

Example: birthday digit reductions.

5. Huge Digit Strings

Sum digits of a string, then condense the total.

Example: 1000-digit input as text.

6. Complexity Practice

Contrast digit loops with O(1) closed form.

Example: “why mod 9?”

Pro Tip: in interviews, walk 9875 on the board first — then surprise with the mod-9 one-liner.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Process Is Visible

    Each digit-sum step is easy to demonstrate on paper.

  2. 2. Clean O(1) Upgrade

    Mod 9 gives the same answer without nested loops.

  3. 3. Tiny Extra Memory

    A few integers suffice — O(1) extra space.

  4. 4. Rich Edge Cases

    0, multiples of 9, and negatives give structured follow-ups.

Pro Tip: memorize both 9 if r == 0 else r and 1 + (n - 1) % 9 — interviewers may ask for either.

Usage Tips

Small habits that keep digital-root solutions interview-ready.

  1. 1. Lead with Iteration

    Show the digit-sum loop before the mod-9 shortcut.

  2. 2. Fix Multiples of 9

    Never return 0 for positive n divisible by 9.

  3. 3. Special-Case Zero

    Digital root of 0 is 0 — handle it before n % 9.

  4. 4. Spot-Check 9875

    Assert the result is 2 — a fast golden test.

  5. 5. Define Negatives

    Say whether you reject or take abs(n).

Pro Tip: for digit strings, sum digit chars mod 9 as you go — you never need the full integer.

Common Pitfalls

Mistakes that commonly break digital-root solutions.

  1. 1. Returning 0 for Multiples of 9

    18 % 9 == 0 but the digital root is 9.

    → Map remainder 0 to 9 when n > 0.

  2. 2. Stopping After One Digit Sum

    9875 → 29 is not yet condensed.

    → Repeat until a single digit remains.

  3. 3. Ignoring Zero

    Naive n % 9 for 0 can be mishandled depending on formula.

    → Return 0 explicitly when n == 0.

  4. 4. Confusing with Digit Count

    Condensing is about digit values, not how many digits exist.

    → Sum digits; do not return the length.

  5. 5. Silent Negative Inputs

    Language-specific % behavior differs for negatives.

    → Document abs() or reject negatives.

Edge Cases

Check these inputs before calling the solution done.

Zero

n = 0

Digital root is 0.

Multiples of 9

n % 9 = 0 and n > 0

Root is 9, not 0.

Single digit

n in 1…9

Already condensed — return unchanged.

Negative input

Define policy

Use abs(n) or reject input explicitly.

Huge values

Beyond integer range

Use string-based digit processing if needed.

Many 9s

e.g. 999…

Root is 9 — good closed-form check.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Congruence. In base 10, n ≡ sum of digits (mod 9).
  • Alternate formula. For n > 0: 1 + (n - 1) % 9.
  • Range. Digital root is always in {0, 1, …, 9}; only 0 maps to 0 among nonnegative ints.
  • Few outer iterations. Digit sum shrinks fast — outer loops stay tiny even for large n.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify classics

  • 9875 → 2
  • 18 → 9
  • 0 → 0

2. Match both methods

  • Iterative vs mod 9
  • Assert equal for many random n

3. Print the chain

  • Show every intermediate sum
  • Explain each step out loud

4. Digit-string input

  • Condense a long numeric string
  • Use running sum mod 9

Notes

  • Condense means repeated digit sums until one digit remains.
  • Methods: iterative reduction and mod 9 shortcut for nonnegative inputs.
  • Handle 0, multiples of 9, and negative-input policy.
  • Closed form is O(1); iterative digit loops stay tiny in practice.

Quick Takeaway: keep summing digits until one remains — or use n % 9 with the 0 / multiples-of-9 fixes.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Iterative digit reductionSmall digit loops (~O(log n) per pass)O(1)
Closed form (mod 9)O(1)O(1)
String-based huge numbersO(d) in digit count dO(1) (+ output chain)

For string-based very large numbers, each pass is linear in the number of digits.

Wrap Up

🎉 Conclusion

Condensing a number is the digital-root problem: sum digits until one remains. Master the iterative loop first, then the mod-9 closed form and its edge cases.

Practice the three examples above, then continue to cube numbers for another classic number-property warm-up.

Handle 0 and multiples of 9 carefully, and explain why mod 9 works in base 10.

💡 Best Practices

✅ Do

  • Show iterative reduction first
  • Special-case 0 in closed form
  • Map ×9 remainder 0 → 9
  • Test 9875 → 2 and 18 → 9
  • Mention the congruence reason

❌ Don’t

  • Stop after a single digit sum
  • Return 0 for positive multiples of 9
  • Ignore zero
  • Leave negatives undefined
  • Skip explaining mod 9

Key Takeaways

Knowledge Unlocked

Five things to remember about condensing a number

Find the digital root the interview-friendly way.

5
Core concepts
9 02

Shortcut

Use mod 9

Math
0 03

Zero

Root is 0

Guard
× 04

×9

Root is 9

Edge
O 05

Speed

Closed form O(1)

Analysis

❓ Frequently Asked Questions

It means repeatedly adding digits until only one digit remains (digital root).
No. Digit sum is one pass. Condensing repeats until result is a single digit.
For n > 0: if n % 9 == 0 then 9 else n % 9. For n == 0, answer is 0.
In base 10, number and sum of digits are congruent modulo 9.
Usually we define this for nonnegative integers; you can use abs(n) if needed.
Iterative method is small digit-processing loops; closed form is O(1).
Return it unchanged — no further reduction is needed.
For n > 0 and n divisible by 9, the digital root is 9 (not 0).

Did you Know? 🔊

For positive numbers, digital root follows 1 + (n - 1) % 9.

Continue to Cube Number

Learn how to check whether an integer is a perfect cube with integer roots and edge cases.

Cube number tutorial →

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