__Problem:__

Input a number from the user and tell whether it is an armstrong number or not. Armstrong number is a number which is equal to the sum of cubes of its digits.

For example 371 is an armstrong number because:

33 73 13=27 343 1=371

In the same way 0 and 1 are also armstrong numbers.

In the same way 0 and 1 are also armstrong numbers.

__Code:__

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/** * @author Hafiz Muhammad Umer */ import java.util.Scanner; public class ArmstrongNumber { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.print("Enter a number: "); int a=in.nextInt(),b=a; while (a!=0) { b-=Math.pow((a % 10),3); a-=a % 10; a/=10; } System.out.print("It is"); if(b!=0) System.out.print(" not"); System.out.println(" an armstrong number"); } } |

__Output:__

Enter a number: 207 It is not an armstrong number

Enter a number: 407 It is an armstrong number

__Explanation:__

- We input a number from the user at line 11 and store it to the variable a. Then we copy it to the variable b also.
- Then a loop will run from line 12 to 17. Each round of loop will extract the right most digit from the variable a and subtract its cube from the variable b. Then it will cut the right most digit from the variable a i.e a number 563 will become 56.
We take the modulus of the number with 10 to obtain its right most digit. For example (165 % 10) = 5__How the left most number from the number is extracted?__To do this, first we subtract the right most digit of the number (as found in the previous step) from the number itself and then divide the answer with ten. For example if we want to cut the right most number of 5456 then we will first take (5456 % 10) = 6. Then we will subtract this 6 from the number i.e 5456-6=5450. Then we will divide this 5450 by 10 i.e (5450 / 10) = 545. In this process 5456 was reduced to 545 i.e its right most digit was eliminated.__How the right most digit of the number is cut?__- The loop keeps on cutting the last digit from the variable a and terminates when there is nothing left in the variable a.
- During the complete cycle of the loop, it will subtract the cube of every digit of the input number from the variable b. If the number is an armstrong numer, there will be 0 left in the variable b. This condition is used to display output.