Armstrong Numbers in Range in Java

Print all Armstrong numbers in a given range.

IntermediateModule 3: Loop ProgramsExample 8 of 25
armstrong-numbers-in-range.java
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 }
22
23 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}

Output

Armstrong numbers between 1 and 1000: 1 153 370 371 407

What's going on

We define a helper to check Armstrong and loop over a range, printing numbers that satisfy the condition.