Java Program to Display Armstrong Numbers Between Intervals Using Function

To understand this example, you should have the knowledge of the following Java programming topics:


To find all Armstrong numbers between two integers, checkArmstrong() function is created. This function checks whether a number is Armstrong or not.

Example: Armstrong Numbers Between Two Integers

public class Armstrong {

    public static void main(String[] args) {

        int low = 999, high = 99999;

        for(int number = low + 1; number < high; ++number) {

            if (checkArmstrong(number))
                System.out.print(number + " ");
        }
    }

    public static boolean checkArmstrong(int num) {
        int digits = 0;
        int result = 0;
        int originalNumber = num;

        // number of digits calculation
        while (originalNumber != 0) {
            originalNumber /= 10;
            ++digits;
        }

        originalNumber = num;

        // 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 == num)
            return true;

        return false;
    }
}

Output

1634 8208 9474 54748 92727 93084 

In the above program, we've created a function named checkArmstrong() which takes a parameter num and returns a boolean value.

If the number is Armstrong, it returns true. If not, it returns false.

Based on the return value, the number is printed on the screen inside main() function.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges