Check Magic Number in C

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
Digit sum

What You’ll Learn

Magic numbers (in this tutorial) collapse by repeated decimal digit sums until one digit remains — and that digit must be 1. This page covers the definition, digital-root intuition, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Definition

Final digit 1

Repeated digit sum until one digit; magic iff that digit is 1.

Digit Sum

% 10 loop

Peel digits with n % 10, accumulate, divide by 10.

Digital Root

Same idea

Magic means digital root equals 1 in base 10.

Range Scan

1–50

List every magic value in a closed interval with the same helper.

Live Preview

Step trace

Watch each digit-sum step before you compile C.

vs Happy

No squares

Happy numbers square digits; magic numbers only sum them.

Introduction

A magic number (for this tutorial) is a positive integer that reduces to 1 when you repeatedly replace it by the sum of its decimal digits. For 19: 1 + 9 = 10, then 1 + 0 = 1 — so 19 is magic.

In C interviews you usually write nested loops (outer until one digit, inner digit sum), then optionally list magic numbers in a range — and clarify that this is not the same as happy numbers.

Why it matters?

It trains digit extraction, nested loops, and digital-root intuition — skills that reappear in happy numbers, Harshad checks, and checksum-style problems.

Key Highlights

Final Digit 1

Only the last single digit decides magic.

Nested Loops

Outer until n ≤ 9; inner sums digits.

19 → 10 → 1

Classic whiteboard trace for interviews.

Not Happy

No squared digits — plain digit sum only.

In short: keep summing decimal digits until one digit remains; the number is magic iff that digit is 1.

📝 Problem & Approach

Given a positive integer n, decide whether it is magic under the repeated digit-sum rule; optionally list every magic value in a closed interval.

c
/* n = 19
 * 19 → 1+9 = 10
 * 10 → 1+0 = 1   → magic
 *
 * n = 18
 * 18 → 1+8 = 9   → not magic
 */

Inputs & Outputs

ItemTypeDescription
number / nintPositive integer to classify (Example 1 uses 19).
Range boundsintInclusive interval such as [1, 50] (Example 2).
Resultflag / textMagic or not; or a printed list of magic values.

Minimal workflow

Pseudocode
function digit_sum(n):   // n >= 0
    s ← 0
    while n > 0:
        s ← s + (n mod 10)
        n ← floor(n / 10)
    return s

function is_magic(n):   // assume n > 0
    while n > 9:
        n ← digit_sum(n)
    return (n = 1)

Method comparison

MethodIdeaExtra space
Nested loopsOuter until one digit; inner digit sumO(1)
Digital-root formula1 + (n - 1) % 9 equals 1O(1)

⚡ Quick Reference

GoalPattern
Next digitsum += num % 10; num /= 10;
Outer reducewhile (num > 9) { ... num = sum; }
Magic testreturn num == 1;
O(1) shortcut1 + (n - 1) % 9 == 1 for n > 0
Classic probesTest 19, 18, and 1

📋 Magic vs Happy vs Harshad

Related digit problems — only magic uses plain digit sum to digital root 1.

Magic
sum → 1

Repeated digit sum ends at 1

Happy
sq sum

Sum of squared digits until cycle / 1

Harshad
n % s(n)

One digit sum, then divisibility

Interview tip
loop first

Mention digital-root formula only if asked

Context

When This Problem Shows Up

Reach for magic-number drills when digit sums and digital roots matter.

  1. Interview warm-ups

    Nested loops, digit extraction, and a clear stop condition.

  2. Digital-root family

    Pairs with happy, Harshad, and other digit walks.

  3. Checksum intuition

    Digit sums appear in simple validation schemes.

  4. Range filters

    List or count magic numbers in [L, R].

  5. Not compiler “magic”

    Unrelated to unexplained numeric literals in source code.

Key benefit: a tiny nested-loop problem that builds the exact muscle memory you need for other digit-property interviews.

🔮 Live Preview

Enter a positive integer to watch the same digit-sum chain as the C code.

Try 19, 18, or 1. Avoid negatives.

Live result
Press “Run check” to see the digit-sum steps.

Examples Gallery

Two complete C programs — classify a single value, and list magic numbers in [1, 50]. Click View Output to reveal sample console results.

📚 Getting Started

Nested digit-sum loops for n = 19.

Example 1 — Single Value: 19

Outer loop continues until one digit; inner loop computes one digit-sum pass.

c
#include <stdio.h>

/* Returns 1 if num is a magic number (repeated digit sum ends at 1), else 0 */
int is_magic_number(int num) {
    while (num > 9) {
        int sum = 0;

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

        num = sum;
    }

    return num == 1;
}

int main(void) {
    int number = 19;

    if (is_magic_number(number)) {
        printf("%d is a Magic Number.\n", number);
    } else {
        printf("%d is not a Magic Number.\n", number);
    }

    return 0;
}

How It Works

The outer while (num > 9) keeps collapsing the value; the inner while is one pass of digit summation. When num is a single digit, compare it to 1.

📈 Practical Patterns

Reuse the same helper across a closed interval.

Example 2 — Magic Numbers in [1, 50]

Scan each i independently; listing matches the classic reference output.

c
#include <stdio.h>

int is_magic_number(int num) {
    while (num > 9) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        num = sum;
    }
    return num == 1;
}

int main(void) {
    printf("Magic Numbers in the range 1 to 50:\n");

    for (int i = 1; i <= 50; ++i) {
        if (is_magic_number(i)) {
            printf("%d ", i);
        }
    }

    printf("\n");
    return 0;
}

How It Works

Reuse is_magic_number for each i. Values congruent to 1 mod 9 (with care at multiples of 9) tend to land here — adjust 50 for other intervals.

🧠 How the Algorithm Checks Magic

1

Start from n

Assume a positive integer (samples use n > 0).

Input
2

Sum digits

While n > 9, replace n by the sum of its decimal digits.

Reduce
3

Compare to 1

When one digit remains, return whether it equals 1.

Decide
=

Verdict ready

For 19, the chain is 19 → 10 → 1 — magic.

🔎 Worked Walkthrough — n = 19

Trace each digit-sum pass until a single digit remains.

StepCurrent nDigit sumNote
1191 + 9 = 10still two digits
2101 + 0 = 1single digit
311 == 1 → magic

By contrast, 18 → 9 stops at 9, so it is not magic.

Use Cases

Where magic-number thinking shows up beyond the interview prompt.

1. Digit Loop Practice

Build fluency with % 10 / /= 10 extraction.

Example: same helper reused for digital-root problems.

2. Nested Loop Warm-Ups

Outer stop condition plus an inner reduction pass.

Example: while (num > 9) wrapping a digit loop.

3. Digital Root Insight

Connect the loop to the closed-form digital root.

Example: 1 + (n - 1) % 9.

4. Range Filters

List or count magic numbers in an interval.

Example: all magic in 1–50.

5. Contrast Happy Numbers

Clarify sum vs sum-of-squares when both appear on a sheet.

Example: previous happy-number page.

6. Related Digit Problems

Harshad and Disarium share digit-walk muscle memory.

Example: Harshad uses one sum, not iteration to 1.

Pro Tip: if the interviewer mentions digital roots, say magic means digital root equals 1 — then offer the loop as your primary solution.

Advantages

Why this approach earns interview points.

  1. 1. Easy to Trace

    Whiteboard steps match the nested-loop structure one-for-one.

  2. 2. Tiny for Fixed-Width Int

    Digit counts shrink quickly; cost is effectively constant in practice.

  3. 3. Reusable Helper

    One is_magic_number powers single checks and range scans.

  4. 4. Optional O(1) Follow-Up

    You can mention the digital-root formula after the loop version.

Pro Tip: implement the loop first; offer 1 + (n - 1) % 9 only as a speed follow-up.

Usage Tips

Small habits that keep magic-number code clean in interviews.

  1. 1. Require Positive n

    State n > 0 at the API boundary before digit work.

  2. 2. Stop at One Digit

    Use while (num > 9), not an arbitrary iteration count.

  3. 3. Contrast Happy Numbers

    Say out loud that you are not squaring digits.

  4. 4. Test 19, 18, and 1

    Magic, not magic, and the single-digit edge case.

  5. 5. Mention Formula Optionally

    Keep the loop as the primary answer unless asked for O(1).

Pro Tip: dry-run 19 on paper (table above) before coding — it locks in both nested loops.

Common Pitfalls

Mistakes that commonly break magic-number solutions in C.

  1. 1. Squaring Digits by Habit

    Happy-number muscle memory can sneak into magic checks.

    → Sum digits only — never square them here.

  2. 2. Stopping After One Pass

    19 → 10 is not finished; you must continue until one digit.

    → Keep the outer while (num > 9) loop.

  3. 3. Treating Zero as Magic

    Digit sum of 0 stays 0, which is not 1.

    → Reject or document n <= 0 as non-magic.

  4. 4. Negatives Without a Policy

    Digit loops on negatives need an explicit rule.

    → Reject negatives, or take absolute value and document it.

  5. 5. Confusing Compiler “Magic Numbers”

    Unexplained literals in code are a different meaning of the phrase.

    → Clarify the digit-sum definition when starting your answer.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single digit

Already 1 — magic with zero reduction passes.

Zero

n = 0

Not classified as magic; digit sum stays 0.

Not magic

n = 18

18 → 9, final digit is not 1.

Magic

n = 28

28 → 10 → 1 — magic.

Sign

Negatives

Reject or document absolute-value handling.

Naming

Other meanings

Compiler “magic numbers” are unrelated literals in source.

🔄 Sample Values

Known results for common interview inputs.

Test numberTypical line printed
1919 is a Magic Number.
1818 is not a Magic Number.
11 is a Magic Number.
2828 is a Magic Number.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Read n from stdin

  • Use scanf and validate n > 0
  • Print a clear magic / not-magic message

2. Count in a range

  • How many magic numbers in [1, 100]?
  • Reuse is_magic_number

3. Print the chain

  • Emit each intermediate digit sum like the live preview
  • End with the single-digit verdict

4. O(1) formula

  • Implement 1 + (n - 1) % 9 == 1
  • Verify it matches the loop on 1–50

Notes

  • Definition. Collapse by summing decimal digits until one digit remains; magic iff that digit is 1.
  • Digital root equals 1 is the same condition for positive base-10 inputs.
  • Nested loops mirror interview explanations cleanly; formula is an optional follow-up.
  • Not the same as happy numbers (squared digits) or Harshad (one-sum divisibility).

Quick Takeaway: keep summing digits until one digit remains; magic iff that digit is 1.

⏱️ Time and Space Complexity

ApproachTime (single n)Extra space
Repeated digit-sum loopsO((log n)²) digit ops for typical intO(1)
Digital-root formulaO(1) arithmeticO(1)
Range [1, U]U times the single-check costO(1)
Wrap Up

🎉 Conclusion

Magic numbers are a small digit-sum exercise with clear interview payoff: nested loops, digital-root intuition, and a sharp contrast with happy numbers. Master the single-check helper and the range scan so you can adapt either stop condition on the spot.

Practice the two examples above, then continue to matrix addition for a 2D array warm-up.

Keep summing digits until one digit remains; magic iff that digit is 1.

💡 Best Practices

✅ Do

  • State the digit-sum-to-1 rule before coding
  • Use nested loops that stop at one digit
  • Test 19, 18, and the single-digit case 1
  • Reuse one helper for range scans
  • Contrast with happy numbers if both appear

❌ Don’t

  • Square digits (that is happy numbers)
  • Stop after a single digit-sum pass
  • Treat zero as magic without a documented rule
  • Ignore negatives or leave sign policy unclear
  • Confuse this with compiler “magic number” literals

Key Takeaways

Knowledge Unlocked

Five things to remember about magic numbers in C

Classify them the interview-friendly way.

5
Core concepts
Σ 02

Loops

Outer + digit sum

Code
03

vs Happy

No squares

Contrast
% 04

Formula

Optional O(1)

Follow-up
O 05

Complexity

O((log n)²)

Analysis

❓ Frequently Asked Questions

A positive integer is magic if you repeatedly replace it by the sum of its decimal digits until one digit remains, and that digit is 1. Example: 19 → 10 → 1, so 19 is magic.
Yes. It is already a single digit and equals 1, so the process stops immediately with a magic result.
No. Happy numbers use the sum of squared digits. Magic numbers in this tutorial only sum digits (no squares).
This page follows the usual interview convention: test only nonnegative inputs; the sample programs assume a positive integer.
The final single digit after repeated digit sums is the digital root (for base 10). Here magic means digital root equals 1.
Each digit-sum pass is O(log n) digits; there are O(log n) passes until the value is under 10, so the overall check is O((log n)²) for an n that fits in a fixed-width int—effectively tiny for 32-bit inputs.
Yes. For n > 0, the digital root is 1 + (n - 1) % 9, which equals 1 exactly when n is magic under this definition. Prefer the loop in interviews unless asked for O(1).
18 → 1+8 = 9, which stops at 9, not 1.

Did you Know? 🔊

Repeatedly summing decimal digits until you reach a single digit is the same idea as the digital root in base 10. For this page, a magic number is one whose digital root is 1 (for example 191+9=101+0=1).

Continue to Matrix Addition

Learn how to add two matrices element-wise with 2D arrays in C.

Matrix Addition 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.

8 people found this page helpful