You are here

Java program to check armstrong number

Java program to check if a number is Armstrong or not. Armstrong number is a number which is equal to the sum of digits raise to the power total number of digits in the number. Some Armstrong numbers are: 0, 1, 4, 5, 9, 153, 371, 407, 8208, etc.

Java programming code

  1. import java.util.Scanner;
  2.  
  3. class ArmstrongNumber
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int n, sum = 0, temp, remainder, digits = 0;
  8.  
  9.       Scanner in = new Scanner(System.in);
  10.       System.out.println("Input a number to check if it is an Armstrong number");      
  11.       n = in.nextInt();
  12.  
  13.       temp = n;
  14.      
  15.       // Count number of digits
  16.      
  17.       while (temp != 0) {
  18.          digits++;
  19.          temp = temp/10;
  20.       }
  21.  
  22.       temp = n;
  23.  
  24.       while (temp != 0) {
  25.          remainder = temp%10;
  26.          sum = sum + power(remainder, digits);
  27.          temp = temp/10;
  28.       }
  29.  
  30.       if (n == sum)
  31.          System.out.println(n + " is an Armstrong number.");
  32.       else
  33.          System.out.println(n + " isn't an Armstrong number.");        
  34.    }
  35.    
  36.    static int power(int n, int r) {
  37.       int c, p = 1;
  38.  
  39.       for (c = 1; c <= r; c++)
  40.          p = p*n;
  41.  
  42.       return p;  
  43.    }
  44. }

Output of program:
Armstrong number Java program output

Download Armstrong number program class file.

Using one more loop in the above code you can generate Armstrong numbers from 1 to n or between two integers, i.e., from a to b where a and b are integers.