Armstrong number in java means three digits having their cubes with their addition is equal to the number. In the following code there are five variables are used for the storing the elements. Armstrong number java is unique and we have to find out in easy way. The Armstrong number java contains the logic of swapping which is easy to implement. Armstrong number in java having count the number of digits and then cube of first digit then add to cube of second and third.
Armstrong java we calculate the reminder and sum to calculate the Armstrong number. Below code contains the Armstrong number program in java with output example.
Java Program for Armstrong Number with Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.Scanner; //Start of Armstrong Number in java class ArmstrongNumber { public static void main(String args[]) { int i, sum = 0; int temp, remainder, digits = 0; Scanner in = new Scanner(System.in); System.out.println("Enter a number to check an Armstrong number"); i = in.nextInt(); temp = i; // Count number of digits while (temp != 0) { //Logic for Armstrong number in java digits++; temp = temp/10; } temp = i; while (temp != 0) { remainder = temp%10; sum = sum + power(remainder, digits); temp = temp/10; } if (i == sum) System.out.println(i + " is an Armstrong number."); else System.out.println(i + " is not an Armstrong number."); } static int power(int i, int r) { int c, p = 1; for (c = 1; c <= r; c++) p = p*i; return p; } } // End of java program for Armstrong number |