Armstrong number in java

Let’s learn armstrong number in java.

Armstrong number in java

Check whether a given number is armstrong number or not is one of the most asked interview question.

An armstrong number is a number that is equal to sum of cube of its own digits.

Let me explain with an example, 153 is an Armstrong number. How?

armstrong number in java

Here is the case of 3 digit armstrong number,

153 = (1 * 1 * 1) + (5 * 5 * 5) + (3 * 3 * 3)

Now cubes of above digits is,

(1 * 1 * 1) = 1

(5 * 5 * 5) = 125

(3 * 3 * 3) = 27

So, 1 + 125 + 27 = 153

Hence 153 is an armstrong number where sum of the cubes of its digits is equal to number itself.

Now let’s see armstrong no in java using scanner and while loop.

// armstrong number program in java
import java.util.Scanner;
public class ArmstrongNumber
{
   public static void main(String[] args)
   {
      int x, y, z = 0, temp;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a number: ");
      x = sc.nextInt();
      temp = x;
      while(x > 0)
      {
         y = x % 10;
         x = x / 10;
         z = z + (y * y * y);
      }
      if(temp == z)
      {
         System.out.println(temp + " is an Armstrong Number.");
      }
      else
      {
         System.out.println(temp + " is not an Armstrong Number.");
      }
      sc.close();
   }
}


Output:

Please enter a number: 153
153 is an Armstrong Number.