Let’s learn java program to check armstrong number.

## Java program to check armstrong number

Java program to check a number is armstrong number or not is most asked interview question for freshers in java.

In this post let us learn to check whether given number is armstrong number or not.

Armstrong number is a positive integer and is sum of cube of its own digits equal to number itself.

In java program for armstrong number first given number (371) is stored in an integer variable ‘num’.

In the next step this value is stored in another integer variable ‘a’.

Next in while loop integer variable ‘a’ is looped until it is equal to zero.

Then on each iteration last digit of variable ‘num’ is stored in remainder.

Also read – prime number program in java

Then using math.pow() function remainder is powered by 3 and added to variable ‘output’.

In the next step last digit is removed from variable ‘a’ after dividing it by 10.

Finally variable ‘num’ and ‘output’ are compared.

Also read – armstrong number program in java using scanner

If it is equal then it is an armstrong number else it’s not.

Let’s check whether a given number is an armstrong number or not using while loop or java program to check armstrong number.

import java.util.*; public class ArmstrongNumberInJava { public static void main(String[] args) { int num = 371, a, remainder, output = 0; a = num; while(a != 0) { remainder = a % 10; output += Math.pow(remainder, 3); a /= 10; } if(output == num) { System.out.println(num + " is an armstrong number."); } else { System.out.println(num + " is not an armstrong number."); } } }

**Output:**

371 is an armstrong number.

### Armstrong number for n digits

Similarly we can check whether a given number is armstrong number or not for n digits.

Also read – java program for armstrong number between 1 to 1000

In the below java program we have used two for loops. First for loop counts number of digits in the given number.

Second for loop computes integer variable output where on each iteration remainder is power by number of digits ‘a’.

public class ArmstrongForLoop { public static void main(String[] args) { int num = 1944, input, remainder, output = 0, a = 0; input = num; for(;input != 0; input /= 10, ++a); input = num; for(;input != 0; input /= 10) { remainder = input % 10; output += Math.pow(remainder, a); } if(output == num) { System.out.println(num + " is an armstrong number."); } else { System.out.println(num + " is not an armstrong number."); } } }

**Output:**

1944 is not an armstrong number.

Also read – 4 digit armstrong number in java

Also read – armstrong number in java using recursion