Armstrong Numbers in Range
Print all Armstrong numbers in a given range.
IntermediateTopic: Module 3: Loop Programs
Java Armstrong Numbers in Range Program
This program helps you to learn the fundamental structure and syntax of Java programming.
public class Main {
private static boolean isArmstrong(int n) {
int temp = n;
int digits = 0;
while (temp != 0) {
digits++;
temp /= 10;
}
temp = n;
int sum = 0;
while (temp != 0) {
int d = temp % 10;
int pow = 1;
for (int i = 0; i < digits; i++) {
pow *= d;
}
sum += pow;
temp /= 10;
}
return sum == n;
}
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
if (isArmstrong(i)) {
System.out.print(i + " ");
}
}
}
}Output
Armstrong numbers between 1 and 1000: 1 153 370 371 407
Understanding Armstrong Numbers in Range
We define a helper to check Armstrong and loop over a range, printing numbers that satisfy the condition.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.