Armstrong Number in Java

Check given number is Armstrong or not


This is the important core java interview program, you may face this type of programs in face to face or written test in interviews.

Before doing the program first of all, we have to know what is Armstrong number.
A number that is the sum of the cubes of its each digit equals to the number itself.

e.g: we have Armstrong numbers 0, 1, 153, 370, and 371 etc..
Take number 153, if the sum of the cubes of its each digit is equal to 153 then it is Armstrong number
(1*1*1)+(5*5*5)+(3*3*3) => 1+125+27=153 then it is Armstrong number
(3*3*3)+(7*7*7)+(1*1*1) => 27+343+1=371 is Armstrong number

Let’s we check it programmatically



public class ArmstrongNumber {
       public static void main(String[] args) {       
              int i=153;
              int number=i;
              int result=0,a;
             
              while(i>0){
                     a=i%10;
                     result=result+(a*a*a);
                     i=i/10;                   
              }
              if(result==number){
                     System.out.println(number+" is Armstrong");
              }
              else{
                     System.out.println(number+" is Not Armstrong");
              }
       }
}


Output:

153 is Armstrong

Let’s understand the flow of  the program


int i=153;  // check number is Armstrong or not
int number=i; //number=153
int result=0,a;//result is store result and a is for calculation


while(i>0){  
153>0 true
15>0 true
1>0 true
0>0 false
a=i%10;
a=153%10
  = 3(remainder)
a=15%10
  = 5
a=1%10
  = 1

result= result+(a*a*a);
0+(3*3*3)=27
27+(5*5*5)= 152
152+(1*1*1) = 153

i=i/10;
}
153/10=15.3(quotient)
i interger so it consider 15 only (i=15)
15/10=1.5
i=1
1/10=0.1
i=0


I hope you guys understood the flow of the program well J  and if any doubts comment below.




No comments:

Post a Comment