Java program to check Armstrong number

A number is called as ARMSTRONG number if,sum of cube of every digit present in the number is equal to the number itself then that number is called as armstrong number.For example the 153 is a armstrong number because 1^3+5^3+3^3=153.

In order to write a program for this we need to grab each and every digit present in the number,find cube of it and then add those resultants.To state that number we shall verify the number with given number and then declare whether it as armstrong or not.Like wise in palindrome program we shall use the number 10 to get the last digit.There fore by applying this method we shall write the code accordingly.

import java.util.*;
class armstrong
{
  public static void main(String arg[])
   {
         Scanner ob = new Scanner(System.in);
         System.out.println("Enter any number to check whether it is armstrong or not:");
         int n = ob.nextInt();
         int r,sum=0,temp = n;
         while(n>0)
          {
             r=n%10;
             n=n/10;
             sum=sum+(r*r*r);
          }
           if(sum==temp)
              System.out.print("Given number " + temp +" is Armstrong");
           else
               System.out.println("Given number " + temp +" is not Armstrong");
     }
}

Explanation:In the above program first we declared the object for the Scanner class and we take a number as input for our program.In the while loop we took the last digit of given number in a sequence manner and then we added them all.In the if statement we cross checked the obtained number with given number and we decide it basing on the statement.

The output of above program is

armstrong
You can download the code.

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s