JAVA program to check whether the given number is an armstrong number or not

JAVA program to check whether the given number is an armstrong number or not

This JAVA program is to check whether the given number is an armstrong number or not.An armstrong number is a number whose sum of cubes of digits is equal to the number itself.For example 153 is an armstrong number as

13 + 53 + 33 = 153.

Logic

We find the remainder of the number and then add the cube of remainder to the sum.We keep doing this till the number does not equal to 0.

Dry Run of the Program

Take input ‘n’ .Let us take a number n=153

Copy the value of ‘n’ into copy variable

1st iteration while(copy!=0)   i.e. (153!=0)

remainder=copy%10;  i.e remainder =153%10  hence remainder=3

sum=sum+remainder*remainder*remainder; i.e. sum=0+3^3  hence sum=27

copy=copy/10; i.e. copy=153/10  ; hence copy=15

2nd iteration while(copy!=0)   i.e. (15!=0)

remainder=copy%10;  i.e remainder =15%10  hence remainder=5

sum=sum+remainder*remainder*remainder; i.e. sum=27+5^3  hence sum=152

copy=copy/10; i.e. copy=15/10  ; hence copy=1

3rd iteration while(copy!=0)   i.e. (1!=0)

remainder=copy%10;  i.e remainder =1%10  hence remainder=1

sum=sum+remainder*remainder*remainder; i.e. sum=152+1^3  hence sum=153

copy=copy/10; i.e. copy=1/10  ; hence copy=0

WHILE LOOP ENDS HERE as COPY=0;

We check the if condition if(sum==n)  i.e. (153==153)

It is true hence we print Armstrong number.

Program

import java.util.*;

class armstrong
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int n,copy,remainder,sum=0;
		System.out.println("Enter the number");

    		n=sc.nextInt();
            	copy=n;
               while(copy!=0)
    	       {
			remainder=copy%10;
       	 		sum=sum+remainder*remainder*remainder;
		        copy=copy/10;
    		}

		if(sum==n)
        		System.out.println(n+" is an Armstrong number");
    		else
		        System.out.println(n+" is not an Armstrong number");
	}
}

Output

Share Me!