Check Armstrong Number in C

Beginner
⏱️ 12 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digits & powers

What You’ll Learn

An Armstrong number equals the sum of its digits each raised to the power of the digit count. This tutorial covers the definition, a live preview, algorithm steps, worked C examples, edge cases, and complexity.

Definition

Sum = n

n is Armstrong when each digit raised to power k (digit count) adds up to n.

Count Digits

Find k

Use a loop dividing by 10 to count digits — that count k is the exponent for every digit.

Digit Loop

% 10 / 10

Extract digits with modulo, add ipow(digit, k), then compare the total to n.

Classic 153

1³+5³+3³

The schoolbook example: 1³ + 5³ + 3³ = 153 — your golden test.

Live Preview

Try any n

Type a number and see each digit-power term plus the final verdict.

O(log n)

Complexity

One check walks each digit once; extra space stays O(1).

Introduction

An Armstrong number (also called a narcissistic number) is a positive integer that equals the sum of its digits each raised to the power of how many digits it has.

For a number n with k digits, compute d1k + d2k + … + dkk. If that sum is n, the number is Armstrong. The classic classroom example is 153: 1³ + 5³ + 3³ = 153.

Why it matters?

It trains digit extraction, counting, and integer powers — three skills that show up constantly in interview number problems.

Key Highlights

Same Exponent

Every digit uses power k — the digit count of n.

1–9 Always Work

Single-digit numbers satisfy d¹ = d, so they are Armstrong.

Keep Original n

Extract digits from a temp copy so you can still compare to n.

Integer Powers

Use ipow (integer loops) — avoid math.h pow rounding traps.

In short: count digits k, sum each digitk, and check whether that sum equals the original number.

📝 Problem & Approach

Given a positive integer n, decide whether it is an Armstrong number.

c
/* Example: n = 153 (k = 3 digits)
   1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
   sum == n  → Armstrong */

Inputs & Outputs

ItemTypeDescription
nintPositive integer to test (this tutorial returns false for n <= 0).
Return / printint (0/1) / text1 / message when the digit-power sum equals n.

Minimal workflow

Pseudocode
function isArmstrong(n):
    if n <= 0:
        return 0
    k = number of digits in n
    sum = 0
    for each digit d in n:
        sum = sum + d^k
    return sum == n

Method comparison

MethodIdeaNotes
Arithmetic loop% 10 / / 10 with ipow(digit, k)Interview classic; O(1) extra space
Power tablePrecompute 0^k..9^k then look up each digitVery readable; same O(log n) time

⚡ Quick Reference

GoalPattern
Digit count kcount digits into k
Next digitdigit = temp % 10
Drop last digittemp /= 10
Add powered digittotal += ipow(digit, power)
Armstrong testtotal == n
3-digit classics153, 370, 371, 407

📋 Arithmetic vs Power Table vs Fixed Cube

All can detect Armstrong numbers — generality differs.

Arithmetic
% 10 / 10

Best default for interviews; integer ipow

Power table
pows[d]

Faster when you reuse the same digit count k

Always ^3
fixed cube

Only correct for 3-digit numbers — avoid as general solution

Interview tip
use k digits

Always set the exponent from the digit count

Context

When This Problem Shows Up

Reach for Armstrong drills when digit loops and powers matter.

  1. Interview warm-ups

    Quick check of modulo loops, exponents, and equality returns.

  2. School / college labs

    Classic first program after learning loops and %.

  3. Range printing tasks

    “Print all Armstrong numbers from 1 to N” reuses one helper.

  4. Teaching digit math

    Makes % 10 and / 10 feel concrete with a famous example.

  5. Not for huge digit counts alone

    Very large k makes powers enormous — discuss constraints in the prompt.

Key benefit: one short problem that covers digits, powers, helpers, and O(log n) reasoning.

🔮 Live Preview

Enter a positive integer to see each digit-power term and the verdict.

Use integers n ≥ 1 (preview capped at 999999999).

Live result
Press "Run check" to see details.

Examples Gallery

Three complete C programs — check one number, print a range, and a digit-power table variant. Click View Output to reveal sample console results.

📚 Getting Started

Arithmetic digit extraction — the interview default.

Example 1 — Check a Single Number

Count digits, sum ipow(d, k) for each digit, then compare with the original value.

c
#include <stdio.h>

static int ipow(int base, int exp) {
    int r = 1;
    int e = exp;

    while (e-- > 0) {
        r *= base;
    }
    return r;
}

/* Returns 1 if n is Armstrong (base 10), 0 otherwise; n > 0 only */
int isArmstrong(int number) {
    int k = 0;
    int t = number;

    if (number <= 0) {
        return 0;
    }

    while (t > 0) {
        k++;
        t /= 10;
    }

    t = number;
    int sum = 0;
    while (t > 0) {
        int d = t % 10;
        sum += ipow(d, k);
        t /= 10;
    }

    return sum == number;
}

int main(void) {
    int number = 153;

    if (isArmstrong(number)) {
        printf("%d is an Armstrong number.\n", number);
    } else {
        printf("%d is not an Armstrong number.\n", number);
    }

    return 0;
}

How It Works

Guard non-positive inputs, count digits into k, then walk digits via a working copy so the original value stays intact for the final comparison. ipow keeps every power in integer arithmetic — no math.h pow.

📈 Practical Patterns

Reuse the helper across a closed range.

Example 2 — Armstrong Numbers in a Range

Loop from start to end and print every value that passes the check.

c
#include <stdio.h>

static int ipow(int base, int exp) {
    int r = 1;
    int e = exp;
    while (e-- > 0) {
        r *= base;
    }
    return r;
}

int isArmstrong(int num) {
    int k = 0;
    int t = num;

    if (num <= 0) {
        return 0;
    }

    while (t > 0) {
        k++;
        t /= 10;
    }

    t = num;
    int sum = 0;
    while (t > 0) {
        int d = t % 10;
        sum += ipow(d, k);
        t /= 10;
    }

    return sum == num;
}

int main(void) {
    int start = 1;
    int end = 200;

    printf("Armstrong numbers in the range %d to %d:\n", start, end);

    for (int i = start; i <= end; ++i) {
        if (isArmstrong(i)) {
            printf("%d ", i);
        }
    }

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

How It Works

Single-digit values appear first (each is Armstrong), then 153 is the only other hit in 1…200. The helper stays pure; the loop only decides what to print.

⚡ Faster Range Scans

Precompute digit powers once per digit count k.

Example 3 — Digit-Power Lookup Table

Build 0^k … 9^k once, then sum with array lookups instead of calling ipow per digit.

c
#include <stdio.h>

static int ipow(int base, int exp) {
    int r = 1;
    while (exp-- > 0) {
        r *= base;
    }
    return r;
}

/* Precompute 0^k .. 9^k, then sum with lookups */
int isArmstrong(int number) {
    int k = 0;
    int t = number;
    int pows[10];
    int sum = 0;
    int i;

    if (number <= 0) {
        return 0;
    }

    while (t > 0) {
        k++;
        t /= 10;
    }

    for (i = 0; i < 10; ++i) {
        pows[i] = ipow(i, k);
    }

    t = number;
    while (t > 0) {
        sum += pows[t % 10];
        t /= 10;
    }

    return sum == number;
}

int main(void) {
    printf("%d\n", isArmstrong(153));
    printf("%d\n", isArmstrong(123));
    return 0;
}

How It Works

After counting k, fill pows[0..9] with i^k. Each digit then costs an array lookup. 153 prints 1; 123 prints 0.

🧠 How the Algorithm Decides

1

Validate n

If n <= 0, return 0 for this tutorial’s positive-integer definition.

Guard
2

Count digits

Set k (power) from the number of digits in n.

Exponent
3

Sum digit powers

Extract each digit and add ipow(digit, k) into a running total.

Accumulate
=

Compare to n

Return true only when the powered digit sum equals the original number.

🔎 Worked Walkthrough — n = 153

Trace the arithmetic method. Digit count k = 3. Start with temp = 153 and total = 0.

tempDigitAddtotal
1533ipow(3, 3) = 2727
155ipow(5, 3) = 125152
11ipow(1, 3) = 1153

Final check: 153 == 153Armstrong.

Use Cases

Where Armstrong checks show up beyond the interview prompt.

1. Interview Coding

Standard warm-up for digit loops and powers.

Example: write isArmstrong(n).

2. Teaching Modulo

Makes % 10 and / 10 memorable with 153.

Example: chalkboard digit peel.

3. Range Filters

Print or count Armstrong numbers inside bounds.

Example: all hits from 1 to 1000.

4. Related Digit Problems

Skills transfer to Armstrong-like and digit-sum variants.

Example: Disarium / automorphic follow-ups.

5. Complexity Practice

Argue O(log n) from digit count convincingly.

Example: “how many loop iterations?”

6. Integer vs Float Talk

Shows why exact integer powers matter for equality.

Example: reject math.pow floats.

Pro Tip: keep one isArmstrong helper and reuse it for single checks and range printers — less duplicated digit logic.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Definition Maps Cleanly

    Count digits, sum powers, compare — almost no translation gap.

  2. 2. Works for Any Digit Length

    Using k from the digit count handles 1-digit through multi-digit cases.

  3. 3. Tiny Extra Memory

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

  4. 4. Easy Self-Checks

    153 / 370 / 371 / 407 and 123 give instant confidence.

Pro Tip: say “exponent equals digit count” out loud before coding — it stops the fixed-cube mistake.

Usage Tips

Small habits that keep Armstrong code interview-ready.

  1. 1. Copy Before Peeling Digits

    Use temp = n so the original value survives for comparison.

  2. 2. Compute Power Once

    Count digits before the sum loop — do not recalculate k each iteration.

  3. 3. Prefer Integer ipow

    Stay exact; floating powers can spoil equality on larger inputs.

  4. 4. Test Positives and Negatives

    Assert 153/370 return 1 and 123 returns 0 before moving on.

  5. 5. Clarify 0 Policy

    Ask whether 0 counts; this page treats only positive integers.

Pro Tip: dry-run 153 on paper once — it catches off-by-one digit-count bugs faster than guessing.

Common Pitfalls

Mistakes that commonly break Armstrong solutions.

  1. 1. Always Cubing Digits

    Hard-coding ^3 fails for 1-digit and multi-digit cases beyond 3.

    → Set the exponent from the digit count every time.

  2. 2. Destroying the Original n

    Looping on n itself leaves nothing to compare against.

    → Peel digits from a temp copy.

  3. 3. Using Float Powers

    math.pow can introduce rounding that breaks equality.

    → Prefer integer ipow.

  4. 4. Skipping Single Digits

    Some students assume only 3-digit examples count.

    → Remember 1–9 are Armstrong under the standard definition.

  5. 5. Ignoring Non-Positive Inputs

    Negative or zero values need an explicit policy.

    → Return false early for n <= 0 in this tutorial.

Edge Cases

Check these inputs before calling the solution done.

n <= 0

Return false

This tutorial uses positive integers only.

1–9

All Armstrong

Single-digit values satisfy d¹ = d.

153

Golden test

Must return true for any correct implementation.

123

Negative case

Sum is 36 — must return 0.

Original n

Keep a copy

Extract digits from temp, compare against n.

Large n

Big powers

Use long long for large power sums; watch time for huge ranges.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • 3-digit set. The only 3-digit Armstrong numbers are 153, 370, 371, and 407.
  • Narcissistic. In number theory, these are often called narcissistic numbers of order k.
  • Order matters. The exponent is the digit count of that specific n — not a global constant.
  • Rare for large k. As digit length grows, Armstrong numbers become sparse.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify the 3-digit set

  • Confirm 153, 370, 371, 407
  • Reject nearby values like 152 and 372

2. Count in a range

  • How many Armstrong numbers are in 1…1000?
  • Reuse isArmstrong

3. No str allowed

  • Count digits with a divide-by-10 loop
  • Same answer as the digit-count loop

4. Print power terms

  • For debugging, print each d^k like the live preview
  • Great for explaining interviews aloud

Notes

  • Exponent = digit count. That single rule separates Armstrong from casual “sum of cubes” shortcuts.
  • Preserve the original n while extracting digits — compare at the end.
  • 1 through 9 are valid Armstrong numbers under this definition.
  • State O(log n) time and O(1) extra space when asked about complexity.

Quick Takeaway: sum each digit raised to the digit-count power; if that equals n, the number is Armstrong.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Single checkO(log n)O(1)
Power-table checkO(log n)O(log n) digit work + O(1) lookups
Range 1…Uabout O(U log U)O(1)
Wrap Up

🎉 Conclusion

Armstrong numbers are a clean digit-power exercise: find k, sum each digitk, and compare with n. Master the arithmetic loop first, then the power-table variant when scanning many values.

Practice the three examples above, then continue to automorphic numbers for another classic digit-pattern check.

Never hard-code cubes for all cases, never overwrite n while peeling digits, and always verify 153.

💡 Best Practices

✅ Do

  • Set the exponent from the digit count
  • Use a temp variable for digit extraction
  • Prefer integer ipow powers
  • Test 153, 370, 1, and 123
  • State O(log n) time when asked

❌ Don’t

  • Hard-code power 3 for every n
  • Mutate n before comparing
  • Rely on floating-point powers
  • Forget that 1–9 are Armstrong
  • Skip the n <= 0 guard

Key Takeaways

Knowledge Unlocked

Five things to remember about Armstrong numbers

Check digit powers the interview-friendly way.

5
Core concepts
k 02

Exponent

k = digit count

Math
% 03

Digits

% 10 and / 10

Code
153 04

Classic

1³+5³+3³

Example
O 05

Complexity

O(log n) time

Analysis

❓ Frequently Asked Questions

In base 10, a positive integer n is an Armstrong number (also called narcissistic) if n equals the sum of its decimal digits, each raised to the power of the total number of digits. Example: 153 has three digits and 1^3 + 5^3 + 3^3 = 153.
Yes. For a one-digit n, the digit count is 1, and n^1 = n, so every digit 1 through 9 is Armstrong. Whether to include 0 depends on the problem statement; this page treats n <= 0 as not Armstrong.
pow works in floating point, which can round incorrectly for larger powers. Integer exponentiation keeps the check exact for typical interview sizes and avoids linking with -lm on some toolchains.
Definitions vary. The sample programs return 0 for n <= 0 so digit counting stays well-defined and matches common contest specs that only ask for positive integers.
The same value k for all digits — where k is the count of digits in n. Do not use a fixed cube unless you only care about 3-digit cases.
Let d be the number of decimal digits. Counting digits and summing digit powers are both O(d), and d is Theta(log n), so the whole test is O(log n) for a fixed base.
The sum of digit powers can exceed 32-bit int before you even compare to n. Use long long for the accumulator (and sometimes for n) when the problem allows large inputs.
Yes in common programming tutorials — both mean the digit-power sum with exponent equal to the digit count equals the number.

Did you Know? 🔊

Besides the trivial one-digit cases 19, the only three-digit Armstrong numbers are 153, 370, 371, and 407. For example, 1³ + 5³ + 3³ = 153.

Continue to Automorphic Number

Learn how to check whether a number’s square ends with the number itself.

Automorphic 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