In this java program, you’ll learn how to display an Armstrong number between two intervals such as 1 to 100 or 1 to nth. In this program, we used the following java basics such as for
loop, while
loop, and if..else
condition.
Here is the code of the program to display an Armstrong number between two intervals.
//Java Program to Display Armstrong Number Between Two Intervals
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Start Number: ");
int low = sc.nextInt();
System.out.println("Enter an End Number: ");
int high = sc.nextInt();
System.out.println("All Armstrong Number Between Intervals of " + low + " to " + high + " are:");
for (int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
}
Enter a Start Number:
1
Enter an End Number:
9999
All Armstrong Number Between Intervals of 1 to 9999 are:
2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
Comments