Thursday 28 January 2016

Write a program in java input a number and check the number is armstrong number or not.

Armstrong Number in Java:

Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371, 407 etc.
 
153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153

Program:
import java.util.*;
class Armstrong
{
  public int arm(int n)
  {
    int rem,sum=0;
    do
    {
      rem=n % 10;
      sum = sum + (rem * rem * rem);
      n= n/10;
    }
    while(n!=0);
    return sum;
  }
  public static void main(String args[])
  {
    int n,temp,res;
    Scanner sc=new Scanner(System.in);
    Armstrong ob=new Armstrong();
    System.out.println("Enter The Number: ");
    n=sc.nextInt();
    temp=n;
    res=ob.arm(n);
    if(res==temp)
    {
      System.out.println("Armstrong Number");
    }
    else
      System.out.println("Not an Armstrong Number");
   
  }
}

Output:
Enter The Number:
153
Armstrong Number

Enter The Number:
105
Not an Armstrong Number

No comments:

Post a Comment