armstrong number in java program code example

Example 1: Armstrong number in java

// Check whether a given number is armstrong number or not
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();
   }
}

Example 2: 4 digit armstrong number in java

// 4 digit armstrong number in java
public class ArmstrongNumberDemo
{
   public static void main(String[] args) 
   {
      int num = 9474, realNumber, remainder, output = 0, a = 0;
      realNumber = num;
      for(;realNumber != 0; realNumber /= 10, ++a);
      realNumber = num;
      for(;realNumber != 0; realNumber /= 10)
      {
         remainder = realNumber % 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.");
      }
   }
}

Tags:

Java Example