Armstrong Number In Java Example
Chapter:
Miscellaneous
Last Updated:
06-04-2016 17:47:23 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class JavaArmstrongNumber {
public static void main(String args[]) {
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
while (temp != 0) {
digits++;
temp = temp / 10;
}
temp = n;
while (temp != 0) {
remainder = temp % 10;
sum = sum + power(remainder, digits);
temp = temp / 10;
}
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
/* ............... END ............... */
Output
Input a number to check if it is an Armstrong number
10
10 is not an Armstrong number.
Input a number to check if it is an Armstrong number
153
153 is an Armstrong number.
Notes:
-
Armstrong number is a number that is equal to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.
Tags
Armstrong Number, Java