/** * An example program that Determining Armstrong number in Java using for loop. */ public class ExampleProgram { public static void main(String[] args) { System.out.println(1 + " is armstrong? " + isArmstrongNumber(1)); System.out.println(2 + " is armstrong? " + isArmstrongNumber(2)); System.out.println(3 + " is armstrong? " + isArmstrongNumber(3)); System.out.println(152 + " is armstrong? " + isArmstrongNumber(152)); System.out.println(153 + " is armstrong? " + isArmstrongNumber(153)); System.out.println(154 + " is armstrong? " + isArmstrongNumber(154)); } public static boolean isArmstrongNumber(int number) { int sum = 0; int n = number; for (; n>0; ) { // get the last digit int digit = n%10; // cube me please and sum sum = sum + (digit * digit * digit); // and remove the digit we processed. n = n / 10; } return number == sum; } }
And we get below output when we run the code above:
1 is armstrong? true 2 is armstrong? false 3 is armstrong? false 152 is armstrong? false 153 is armstrong? true 154 is armstrong? false