Armstrong Number Program in Java
In this lesson: Check Armstrong number in Java with digits and power — code, step-by-step dry run and output. Copy & run. In Hindi & English.
What is an Armstrong number
An Armstrong number (for 3 digits) equals the sum of the cubes of its own digits. The classic example is 153: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153. Checking one is a great exercise in extracting digits and using a loop.
Extracting digits
int num = 153;
while (num > 0) {
int digit = num % 10; // last digit
System.out.println(digit);
num = num / 10; // remove last digit
}
5
1
The trick % 10 gets the last digit and / 10 removes it. Repeating peels digits off from right to left until the number becomes 0.
The Java program
public class Armstrong {
public static void main(String[] args) {
int num = 153;
int original = num; // keep a copy
int sum = 0;
while (num > 0) {
int d = num % 10;
sum += d * d * d; // cube each digit
num = num / 10;
}
if (sum == original)
System.out.println(original + " is Armstrong");
else
System.out.println(original + " is not Armstrong");
}
}
We save original, then loop: take each digit, add its cube to sum, and remove the digit. At the end we compare sum with the original number.
Dry run
| Step | temp | d = temp%10 | sum += d*d*d | temp /= 10 |
|---|---|---|---|---|
| 1 | 153 | 3 | 0 + 27 = 27 | 15 |
| 2 | 15 | 5 | 27 + 125 = 152 | 1 |
| 3 | 1 | 1 | 152 + 1 = 153 | 0 |
| 4 | 0 | temp==0 stops. sum(153) == num(153) → Armstrong! | ||
Each turn peels off the last digit with %10, cubes it into sum, then drops it with /10. When the sum of cubes equals the original number, it is Armstrong.
For any number of digits
A true Armstrong number raises each digit to the power of the number of digits, not always 3. For a 4-digit number, you cube... no, you use the 4th power. So count the digits first, then raise each digit to that power. The 3-digit version above uses cubes because it has 3 digits.
Common mistakes
- Not saving the original. The loop reduces the number to 0 — keep a copy to compare.
- Wrong power. For n digits, raise each digit to the n-th power, not always 3.
- Swapping % and /.
% 10gets the digit;/ 10removes it. - Wrong loop condition. Loop while
num > 0to process all digits.
Summary
- An Armstrong number equals the sum of its digits raised to the digit-count power.
- For 3 digits, that means the sum of cubes (153 = 1³+5³+3³).
- Get digits with
% 10and remove them with/ 10. - Save the original number to compare at the end.
- Compare the sum to the original to decide.
Next, practise digit work in the palindrome number program, or loops in Java loops.
Frequently Asked Questions
What is an Armstrong number?
How do I extract the digits of a number?
digit = num % 10 to get the last digit, then num = num / 10 to remove it. Repeat in a loop until num becomes 0. This peels off digits from right to left.