Placement Prep

Armstrong Numbers in a Range: C, C++, Java, Python

Programs to print Armstrong numbers between two intervals in C, C++, Java, Python. Traced algorithm, integer-power fix, and time complexity.

By FACE Prep Team 6 min read
programs c-programming java python algorithms placement-prep number-theory

A number with n digits is Armstrong if the sum of its digits, each raised to the nth power, equals the number itself. For 153: 1³ + 5³ + 3³ = 153.

Printing all such numbers between two given intervals is a standard range-iteration problem. It appears in AMCAT Automata, Wipro NLTH, and most company-level coding rounds that test loops and modulo arithmetic. Two loops per candidate number (one to count digits, one to compute the power sum) is all the structure needed.

What Is an Armstrong Number

The formal name is narcissistic number. A positive integer n with d digits is narcissistic if the sum of its digits each raised to the dth power equals n.

This means the exponent is not fixed at 3. It changes based on how many digits the number has. For 3-digit numbers the test is a cube sum; for 4-digit numbers it is a fourth-power sum.

Verified examples:

  • 153 (3 digits): 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
  • 370 (3 digits): 3³ + 7³ + 0³ = 27 + 343 + 0 = 370 ✓
  • 371 (3 digits): 3³ + 7³ + 1³ = 27 + 343 + 1 = 371 ✓
  • 407 (3 digits): 4³ + 0³ + 7³ = 64 + 0 + 343 = 407 ✓
  • 1634 (4 digits): 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634 ✓

A commonly asked follow-up: are there any two-digit Armstrong numbers?

  • Maximum sum of squares of two digits: 9² + 9² = 162 (a 3-digit result).
  • No integer from 10 to 99 can satisfy the condition.
  • Two-digit Armstrong numbers do not exist.

All single-digit integers from 1 to 9 are trivially Armstrong: each equals its own first power.

Algorithm for the Range

To find all Armstrong numbers in [start, end]:

  • Step 1: Loop i from start to end.
  • Step 2: Count the digits of i by repeatedly dividing by 10 until the quotient reaches 0.
  • Step 3: Loop through the digits of i again, raise each digit to the power found in Step 2, and accumulate the sum.
  • Step 4: If the accumulated sum equals i, print i.

This is the same digit-extraction pattern used in sum-of-digits programs: extract the rightmost digit with n % 10, drop it with n / 10, repeat.

One implementation note: avoid pow(digit, d) from <math.h>. That function returns a double, and floating-point rounding can silently produce 26.9999 instead of 27. Casting to int then gives 26, causing 371 to fail the test incorrectly. A manual integer-power function (a simple multiply loop) fixes this with no performance cost.

Traced Example: 100 to 999

For input 153:

  • Count digits: 153 / 10 = 15 (digits=1), 15 / 10 = 1 (digits=2), 1 / 10 = 0 (digits=3). Total: d = 3.
  • Power sum, temp = 153:
    • digit = 153 % 10 = 3, 3³ = 27, sum = 27, temp = 15
    • digit = 15 % 10 = 5, 5³ = 125, sum = 152, temp = 1
    • digit = 1 % 10 = 1, 1³ = 1, sum = 153, temp = 0
  • sum (153) == i (153): Armstrong. Print 153.

For input 154:

  • d = 3 (same count loop).
  • Power sum: 1³ + 5³ + 4³ = 1 + 125 + 64 = 190.
  • 190 ≠ 154: not Armstrong.

Running the algorithm over 100 to 999 produces exactly four Armstrong numbers: 153, 370, 371, 407.

Programs in C, C++, Java, and Python

C

#include <stdio.h>

int intPow(int base, int exp) {
    int result = 1;
    for (int i = 0; i < exp; i++) result *= base;
    return result;
}

int isArmstrong(int n) {
    int temp = n, digits = 0, sum = 0;
    while (temp > 0) { digits++; temp /= 10; }
    temp = n;
    while (temp > 0) {
        int d = temp % 10;
        sum += intPow(d, digits);
        temp /= 10;
    }
    return sum == n;
}

int main() {
    int start, end;
    printf("Enter start and end: ");
    scanf("%d %d", &start, &end);
    printf("Armstrong numbers between %d and %d:\n", start, end);
    for (int i = start; i <= end; i++) {
        if (i > 0 && isArmstrong(i)) printf("%d\n", i);
    }
    return 0;
}

C++

#include <iostream>
using namespace std;

int intPow(int base, int exp) {
    int result = 1;
    for (int i = 0; i < exp; i++) result *= base;
    return result;
}

bool isArmstrong(int n) {
    int temp = n, digits = 0, sum = 0;
    while (temp > 0) { digits++; temp /= 10; }
    temp = n;
    while (temp > 0) {
        int d = temp % 10;
        sum += intPow(d, digits);
        temp /= 10;
    }
    return sum == n;
}

int main() {
    int start, end;
    cout << "Enter start and end: ";
    cin >> start >> end;
    cout << "Armstrong numbers between " << start << " and " << end << ":\n";
    for (int i = start; i <= end; i++) {
        if (i > 0 && isArmstrong(i)) cout << i << "\n";
    }
    return 0;
}

Java

import java.util.Scanner;

public class ArmstrongRange {

    static int intPow(int base, int exp) {
        int result = 1;
        for (int i = 0; i < exp; i++) result *= base;
        return result;
    }

    static boolean isArmstrong(int n) {
        int temp = n, digits = 0, sum = 0;
        while (temp > 0) { digits++; temp /= 10; }
        temp = n;
        while (temp > 0) {
            int d = temp % 10;
            sum += intPow(d, digits);
            temp /= 10;
        }
        return sum == n;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter start and end: ");
        int start = sc.nextInt();
        int end = sc.nextInt();
        System.out.println("Armstrong numbers between " + start + " and " + end + ":");
        for (int i = start; i <= end; i++) {
            if (i > 0 && isArmstrong(i)) System.out.println(i);
        }
    }
}

Python

def int_pow(base, exp):
    result = 1
    for _ in range(exp):
        result *= base
    return result

def is_armstrong(n):
    digits = len(str(n))
    return sum(int_pow(int(d), digits) for d in str(n)) == n

def print_armstrong_in_range(start, end):
    print(f"Armstrong numbers between {start} and {end}:")
    for i in range(max(start, 1), end + 1):
        if is_armstrong(i):
            print(i)

start = int(input("Enter start: "))
end = int(input("Enter end: "))
print_armstrong_in_range(start, end)

Sample output for range 1 to 1000:

1
2
3
4
5
6
7
8
9
153
370
371
407

Time and Space Complexity

For a range [start, end] where the span is n = end minus start:

  • Time complexity: The outer loop runs n iterations. For each number, the inner digit-count and power-sum loops each run d times, where d = number of digits. Since d = floor(log10(end)) + 1, the total time is O(n × log end).
  • Auxiliary space: O(1). Only a fixed set of integer variables (temp, digits, sum, d) are used regardless of range size.

For context on auxiliary space vs. total space complexity, see the space complexity guide. The range-iteration structure here closely follows the pattern in counting integers with a specific numeric property in a range: outer range loop, inner property check per candidate.

The GeeksforGeeks Armstrong range program uses pow() from <math.h>; the manual intPow above avoids float truncation without any change to asymptotic complexity.

Common Mistakes

  • Using pow() directly: (int)pow(3, 3) can return 26 on some compilers due to double rounding. Use integer multiplication instead.
  • Fixing the exponent at 3: Armstrong checking requires the exponent to match the digit count of the current number. For a range that includes 4-digit numbers, each 4-digit candidate uses exponent 4.
  • Starting the range at 0: The digit-count loop while (temp > 0) exits immediately for 0, leaving digits = 0 and sum = 0. Since 0 == 0, the check passes. Add if (i > 0) as a guard unless 0 is explicitly required.
  • Off-by-one on the range bound: Use i <= end (not i < end) to include the end value.

The digit-extraction loop in this program (extract rightmost digit, accumulate, divide) is the same pattern used in every modulo-based number property check: digit sum, perfect numbers, strong numbers. Getting it right once means the rest of the family transfers automatically.

That loop logic also maps cleanly onto API response parsing: extract a field, process it, move to the next record. TinkerLLM lets you take that same accumulate-and-check thinking into a real LLM pipeline at ₹299, where the “digit” is an API response token and the “property check” is an output classifier.

Primary sources

Frequently asked questions

What is the Armstrong number rule for different digit counts?

A number with n digits is Armstrong (narcissistic) if the sum of its digits each raised to the nth power equals the number. For 3-digit numbers, use the cube of each digit; for 4-digit numbers, use the fourth power. The exponent changes with the number, not with the range.

Are there any two-digit Armstrong numbers?

No. The maximum possible sum of squares of two digits is 9 squared plus 9 squared = 162, which is a 3-digit number, so no 2-digit number can satisfy the condition. Every 2-digit number from 10 to 99 fails the test.

What are all Armstrong numbers from 1 to 9999?

1, 2, 3, 4, 5, 6, 7, 8, 9 (single-digit); 153, 370, 371, 407 (3-digit); 1634, 8208, 9474 (4-digit). There are no 2-digit Armstrong numbers.

Why avoid pow() from math.h for Armstrong number checks?

pow() returns a double, and floating-point rounding can produce results like 26.9999 instead of 27. Casting that to int gives 26, causing numbers like 371 to fail incorrectly. A simple manual power function using integer multiplication avoids this entirely.

What is the time complexity of printing Armstrong numbers in a range?

O((end minus start) times d) where d is the number of digits in each number. Since d = floor(log10(n)) + 1, the full complexity is O((end minus start) times log end) in terms of input value.

Is 0 an Armstrong number?

Technically yes: 0 has 1 digit, and 0 to the power 1 equals 0. Most placement problems start the range from 1, so 0 is rarely included. If your range starts at 0, add a guard or treat it as a special case.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF