Display Armstrong Number Using Loops in Java


Write a Java Program to display Armstrong number between two intervals using loops.

Click Here to View the Solution!
public class FindArmstrong {
    public static void main(String[] args) {
        int low = 99, high = 99999;
        for(int number = low + 1; number < high; ++number) {
            int digits = 0;
            int result = 0;
            int originalNumber = number;
            // calculates of number of digits
            while (originalNumber != 0) {
                originalNumber /= 10;
            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 + " ");
Click Here to View the Output!
153 370 371 407 1634 8208 9474 54748 92727 93084 
Click Here to View the Explanation!
  • This program is used to check that whether a number between two intervals is an Armstrong number or not.
  • Initially, for the intervals, tow integer variable low and high are set as low = 99 and high = 99999.
  • A for loop holds an initialization (number = low + 1), a conditional expression (number < high) and an expression to update a variable (++number). This loop allows the program to check every number in the interval low and high.
  • This program uses two while loops and the for loop holds the first while loop in its body, which is used to calculate the number of digits in the originalNumber and stores it in the variable digit.
  • Whereas, the second while loop is used to calculate the remainder of the originalNumber and the result by powering the remainder with the number of digits in every iteration.
  • In the end of the loop, the number is divided by 10 in order to remove the last digit of originalNumber.
  • After the loop exits, both the result and the number are compared. If both are equal, the number is an Armstrong number and is printed.
  • At the end of each iteration, both the digits and the result are reset to 0 within the while loop.