Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are only six Armstrong numbers present between 0 to 999. For example:

0 = 03 = 0

1 = 13 = 1

153 = 13 + 53 + 33 = 1 + 125 + 27 = 153

370 = 33 + 73 + 03 = 27 + 343 + 0 = 370

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

407 = 43 + 03 + 73 = 64 + 0 + 343 = 407

As we can see the given numbers are equal to the sum of cube of its digits. Hence, they are Armstrong number.

The following Java program demonstrates how to check a given number is an Armstrong number or not by using a while loop.

Iterative Approach

Filename: ArmstrongNumberExample.java

Output:

Explanation: The approach is quite straight-forward. In the first step, we assign the given number to a temporary variable named tempVar. It generates a copy of the variable no. After that, determine the remainder of the assigned no by using the modulo operator (no % 10) and the remainder store in the variable dig.

Now we find the cube of the remainder and resultant added to the variable sum. To remove the, we divide the no by 10 (no = no / 10). The same process is repeated till the given number is reduced to 0. Finally, we compare the copy of the given number with the value present in the sum variable. If the comparison between the copy (tempVar) and the sum variable yields true, then we can say the given number is an Armstrong number else not.

Let us discuss the recursive approach too.

Recursive Approach

Filename: ArmstrongNumberExample1.java

Output:

Explanation: In the recursive approach also, we are doing the same thing. Firstly, we generate a copy of the given number. Then, reducing the number to 0 by removing its last digit and adding the cube of the last digit in sum variable. Finally, making a comparison to achieve the result.

Note: A negative number never become an Armstrong number.

Armstrong Numbers Between the Two Numbers

We can also find the Armstrong number between the two given numbers. The following code illustrates the same.

Filename: ArmstrongNumberExample2.java

Output:

Pin It on Pinterest

Share This