Java Program to Display Armstrong Numbers Between Intervals Using Function

In this program, you'll learn to display all armstrong numbers between two given intervals, low and high, using a function in Java.

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;
    }
}

When you run the program, the output will be:

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, number is printed on the screen inside main() function.