Java Examples

Java program to find armstrong number

Table of Contents

Armstrong.java

import java.util.Scanner;

/**
 *  An Armstrong number of three digits is an integer,
 *  where the sum of the cubes of its digits is equal to the given number.
 *  @author Candid Java
 */
public class Armstrong {
 static Scanner scan;

 public static void main(String[] args) {
  scan = new Scanner(System.in);
  System.out.println("please enter the number");

  /**  Let's take 371
   *  3^3 + 7^3 + 1^3 = 371 
   *  If you add those all numbers, the final digit 
   *  should be same as given number
   */

  int n = Integer.parseInt(scan.nextLine()); //n is the number to check armstrong  
  int remainder, sum = 0, temp = 0;
  temp = n;
  while (n > 0) {
   remainder = n % 10;
   sum = sum + (remainder * remainder * remainder);
   n = n / 10;
  }
  if (sum == temp) {
   System.out.println("The Number is Armstrong");
  } else {
   System.out.println("The Number is Not Armstrong");
  }
 }
}

Output

please enter the number
371
The Number is Armstrong