Armstrong Number Program in Java
Armstrong Numbers are numbers whose sum of individual digits raised to cubic power results in the original number.
Example: 153 = 13+53+33=1+125+27 =153, thus 153 is an Armstrong Number.
The algorithm will be:
- Enter and Store the Integer Input.
- Create a duplicate of the input for later comparison.
- Run a While loop construct such that it will run until the input is not reduced to 0.
- Extract each individual digit of the input using Modulus Operator.
- Perform Cumulative Sum of the Cubic Power of each digit extracted.
- After the loop terminates, compare the duplicate of the user input with the cumulative sum.
- If the result of comparison is true, the input is an Armstrong number.
- Print the result accordingly.
import java.util.*;
class Armstrong
{
public static void main()
{
Scanner inp=new Scanner(System.in);
System.out.print("\n Enter Number: ");
int n=inp.nextInt();
int a,s=0,m=n;
while(n!=0) // Extracting each digits and raising them to cubic power while accumulating its sum.
{
a=n%10;
s=s+(a*a*a);
n=n/10;
}
if(s==m) // Checking if sum is equal to original number.
System.out.println(m+" is an Armstrong Number");
else
System.out.println(m+" is not an Armstrong Number");
}
}
Output:
Enter Number: 153
153 is an Armstrong Number
Enter Number: 306
306 is not an Armstrong Number
Report Error/ Suggestion