Armstrong Number Check: Python, C, C++ and Java Programs
Programs to check if a number is Armstrong in Python, C, C++, and Java. Algorithm walkthrough, verified digit-power examples, and a range-finder.
An Armstrong number equals the sum of its own digits each raised to the power of the total digit count: the four 3-digit Armstrong numbers are 153, 370, 371, and 407.
This type of problem appears in placement coding rounds at companies like TCS, Infosys, and Wipro. It tests the digit-extraction loop pattern: a building block for palindrome checks, digit sums, digital roots, and similar exercises. This article covers the definition with verified examples, the algorithm step by step, and programs in Python, C, C++, and Java.
What makes a number an Armstrong number?
A number with n digits is an Armstrong number if the sum of each digit raised to the power n equals the number itself. The key variable is n: for 3-digit numbers the exponent is 3, for 4-digit numbers the exponent is 4, and for 1-digit numbers the exponent is 1.
The formal name in mathematics is narcissistic number. The term “Armstrong number” is the standard name in Indian placement prep material; both refer to the same class of integers. The OEIS sequence A005188 lists all narcissistic numbers in base 10, starting: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, …
Verified examples (arithmetic re-derived from first principles):
- 153 (3 digits, power = 3): 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
- 370 (3 digits, power = 3): 3³ + 7³ + 0³ = 27 + 343 + 0 = 370 ✓
- 371 (3 digits, power = 3): 3³ + 7³ + 1³ = 27 + 343 + 1 = 371 ✓
- 407 (3 digits, power = 3): 4³ + 0³ + 7³ = 64 + 0 + 343 = 407 ✓
- 1634 (4 digits, power = 4): 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1 + 1296 + 81 + 256 = 1634 ✓
- 100 (3 digits, power = 3): 1³ + 0³ + 0³ = 1, which is not 100 ✗
Note on edge cases: all single-digit numbers (0 through 9) are Armstrong numbers because any digit raised to the power 1 equals itself. There are no 2-digit Armstrong numbers; the arithmetic never works out for any two-digit integer.
Algorithm to check an Armstrong number
The logic is a two-pass loop:
- Count the digits. Store the count in a variable (commonly
nordigits). Python does this withlen(str(number)); C, C++, and Java use a while-loop that divides by 10 until the number reaches zero. - Initialise. Save the original number. Set
total = 0andtemp = number. - Extract and power. While
tempis not zero:- Compute
remainder = temp % 10(the rightmost digit). - Add
remainderraised to the digit-count power tototal. - Set
temp = temp // 10to drop the rightmost digit.
- Compute
- Compare. If
total == original, the number is Armstrong. Otherwise, it is not.
The % 10 and // 10 operations are the core digit-extraction idiom. If you have worked through Python example programs for practice or the sum of array elements in Python, you have seen the same accumulate-and-shift pattern applied to different aggregation problems.
Armstrong number program in Python
# Python program to check whether a number is Armstrong or not
number = int(input("Enter a number: "))
total = 0
temp = number
n = len(str(number)) # digit count
while temp != 0:
digit = temp % 10
total += digit ** n
temp //= 10
if total == number:
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
How it works:
len(str(number))converts the integer to a string and counts characters, giving the digit count without a separate loop.totalis used instead of Python’s built-insum()to avoid shadowing the built-in function name.digit ** nuses Python’s exponentiation operator. The result is an exact integer, unlikepow()in C/C++ which returns a float.
Sample run for 153:
n = 3,total = 0,temp = 153- Iteration 1:
digit = 3,total = 0 + 27 = 27,temp = 15 - Iteration 2:
digit = 5,total = 27 + 125 = 152,temp = 1 - Iteration 3:
digit = 1,total = 152 + 1 = 153,temp = 0 total (153) == number (153): Armstrong ✓
Armstrong number program in C
Compile with: gcc armstrong.c -o armstrong -lm
#include <stdio.h>
#include <math.h>
int main() {
int n, original, total = 0, digits = 0;
printf("Enter a number: ");
scanf("%d", &n);
original = n;
/* Pass 1: count digits */
int temp = n;
while (temp != 0) {
digits++;
temp /= 10;
}
/* Pass 2: sum digit powers */
temp = n;
while (temp != 0) {
int rem = temp % 10;
total += (int)pow(rem, digits);
temp /= 10;
}
if (total == original)
printf("%d is an Armstrong number\n", original);
else
printf("%d is not an Armstrong number\n", original);
return 0;
}
Two loops run in sequence. The first counts digits by repeatedly dividing by 10. The second extracts each digit with rem = temp % 10, raises it to the digit-count power using pow(), and accumulates the total. The (int) cast converts the double return value of pow() to an integer. For numbers up to 9 digits, floating-point precision does not affect the result in practice.
Edge case note: if n = 0, the digit-counting loop never executes and digits stays at zero. The digit-power loop also never executes, so total stays at zero. The comparison 0 == 0 returns true, which correctly identifies 0 as an Armstrong number. No special handling is needed for placement test inputs.
Armstrong number program in C++
The C++ version replaces printf/scanf with cout/cin and uses <cmath> instead of <math.h>:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n, original, total = 0, digits = 0;
cout << "Enter a number: ";
cin >> n;
original = n;
int temp = n;
/* Pass 1: count digits */
while (temp != 0) {
digits++;
temp /= 10;
}
/* Pass 2: sum digit powers */
temp = n;
while (temp != 0) {
int rem = temp % 10;
total += (int)pow(rem, digits);
temp /= 10;
}
if (total == original)
cout << original << " is an Armstrong number" << endl;
else
cout << original << " is not an Armstrong number" << endl;
return 0;
}
The algorithmic logic is identical to the C version. The only differences are the I/O functions and using namespace std;. This is a useful pattern to keep in mind during placement prep: C and C++ share the same algorithmic core for most coding test problems; the syntax differences are minor.
Armstrong number program in Java
import java.util.Scanner;
public class ArmstrongCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int original = n;
int digits = String.valueOf(n).length();
int total = 0;
int temp = n;
while (temp != 0) {
int rem = temp % 10;
total += (int) Math.pow(rem, digits);
temp /= 10;
}
if (total == original)
System.out.println(original + " is an Armstrong number");
else
System.out.println(original + " is not an Armstrong number");
}
}
Java uses String.valueOf(n).length() to count digits, similar to Python’s len(str(number)). Math.pow() returns a double, so the cast to int is required. The while-loop body is the same three-line pattern as C and C++.
Finding all Armstrong numbers in a range
To find every Armstrong number between two values, wrap the check in a helper function and iterate:
def is_armstrong(n):
if n < 0:
return False
digits = len(str(n))
total = 0
temp = n
while temp != 0:
digit = temp % 10
total += digit ** digits
temp //= 10
return total == n
# Print all Armstrong numbers from 1 to 9999
for num in range(1, 10000):
if is_armstrong(num):
print(num)
Output for 1 to 999: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407
The helper-function pattern here mirrors how the greatest of three numbers in Python article wraps a conditional check inside a reusable function. A Python calculator program extends the same input-and-loop approach to arithmetic operations.
Time and space complexity
| Metric | Value | Notes |
|---|---|---|
| Time complexity | O(d) | d = number of digits in the input |
| Space complexity | O(1) | A fixed set of integer variables regardless of input size |
| Digit-count pass | O(d) | One division per digit until the number reaches zero |
| Digit-power pass | O(d) | One modulo + power operation per digit |
The two passes together are O(d) + O(d) = O(d). For a 9-digit integer, d = 9, so the check is effectively constant-time for all inputs that appear in placement coding tests. The pow() or ** operation on a single digit (0 through 9) raised to a single-digit power (1 through 9) is O(1) in practice.
Why this pattern matters beyond the test
The temp % 10 and temp //= 10 idiom in the Armstrong check is the same digit-extraction pattern used in palindrome checkers, digit-sum programs, and number-reversal exercises. Knowing it by memory lets you adapt it to any of those problem types in under two minutes.
The next level is reviewing your own implementation with a language model: ask it to find edge cases (what happens for n = 0 or single-digit inputs?), suggest a cleaner Python one-liner, or translate your solution to a different language. TinkerLLM gives you a live Python environment for that kind of iterative code review starting at ₹299.
Primary sources
Frequently asked questions
What is an Armstrong number?
An Armstrong number of n digits is an integer equal to the sum of each of its digits raised to the power n. For 3-digit numbers the exponent is 3. Example: 153 = 1 cubed + 5 cubed + 3 cubed = 1 + 125 + 27 = 153. All single-digit numbers 0 through 9 are Armstrong numbers because any digit raised to the power 1 equals itself.
Which are the four 3-digit Armstrong numbers?
The four 3-digit Armstrong numbers are 153 (1+125+27=153), 370 (27+343+0=370), 371 (27+343+1=371), and 407 (64+0+343=407). No other 3-digit number has digit-cubes that sum to the number itself.
Is 1 an Armstrong number?
Yes. 1 is a 1-digit number, so the digit count is 1. The check computes 1 raised to the power 1, which equals 1. All single-digit numbers from 0 through 9 are Armstrong numbers by the same logic.
Are there Armstrong numbers with more than 3 digits?
Yes. For 4-digit numbers the exponent is 4. Verified examples: 1634 (1+1296+81+256=1634) and 9474 (6561+256+2401+256=9474). The algorithm in this article handles any digit count automatically by computing the digit count first.
What is the time complexity of the Armstrong number check?
O(d) where d is the number of digits in the input. The algorithm makes one pass to count digits and one pass to extract and power each digit. For 9-digit integers, d is 9, so the check is effectively constant-time for all practical placement test inputs.
How do I find all Armstrong numbers in a range in Python?
Write an is_armstrong(n) function and loop over the range, collecting numbers that return True. The range-finder section of this article includes a ready-to-run Python implementation. For the range 1 to 999, all four 3-digit Armstrong numbers (153, 370, 371, 407) will appear in the output.
Why is an Armstrong number also called a narcissistic number?
The mathematical term is narcissistic number: the number is perfectly described by a function of its own digits, a self-referential property. The name Armstrong became common in programming textbooks and placement prep material. Both terms refer to the same class of numbers. The OEIS entry A005188 lists all narcissistic numbers in base 10.
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)