Armstrong Numbers in Range in Java
List Armstrong numbers from 1 to 1000 in Java with an isArmstrong helper and nested digit-power loops. Every positive one-digit number also qualifies.
1public class Main {2 private static boolean isArmstrong(int n) {3 int temp = n;4 int digits = 0;5 while (temp != 0) {6 digits++;7 temp /= 10;8 }9 temp = n;10 int sum = 0;11 while (temp != 0) {12 int d = temp % 10;13 int pow = 1;14 for (int i = 0; i < digits; i++) {15 pow *= d;16 }17 sum += pow;18 temp /= 10;19 }20 return sum == n;21 }2223 public static void main(String[] args) {24 for (int i = 1; i <= 1000; i++) {25 if (isArmstrong(i)) {26 System.out.print(i + " ");27 }28 }29 }30}
Sample Output
Armstrong numbers between 1 and 1000: 1 153 370 371 407
Single-digit matches print first, followed by the four three-digit matches. The earlier abbreviated output omitted valid values 2 through 9.
In this one
- Reuse a number-test helper
- Separate testing from range printing
- Include single-digit Armstrong values
How it works
- 1
Visit i from 1 through 1000.
- 2
Count digits inside isArmstrong.
- 3
Add each digit raised to that count.
- 4
Print i only when the helper returns true.
Edge cases
One-digit candidates
Test 9
9 raised to one equals 9, so it belongs in the output.
Upper endpoint
Test 1000
1 to the fourth plus three zero powers is 1, so 1000 does not pass.
What's going on
Find every Armstrong number from 1 through 1000. An Armstrong number equals the sum of each digit raised to the number of digits. A range search is useful for seeing that a number test can be reused rather than copied for every candidate.
The helper isArmstrong checks one input and returns a boolean, a true-or-false value. It counts the digits, calculates each digit power with a loop, and compares their sum with the original number. The outer loop calls that helper for every i from 1 to 1000 and prints only the successful candidates.
All one-digit positive numbers qualify because raising a digit to power one gives the digit itself. The output therefore includes 1 through 9, not just 1. The other matches in this range are 153, 370, 371, and 407. Changing the range does not change the definition, but much larger inputs would need attention to number-size limits.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does 7 appear in this range output?
Pick an answer to check it.
Question 2
What does the helper return?
Pick an answer to check it.
Questions people ask
Why are 2 through 9 included?
The exponent is one for a one-digit number, so each digit equals its own first power.
Does the code print a heading?
No. It prints only matching numbers and spaces.
Why use a helper method?
It keeps the rule for one candidate separate from the loop that selects a range.