Wednesday, May 28, 2014

Check if a number is Armstron or not.

Note- A number is armstrong if the sum of the cubes of digit of number is equal to the number.
ex- 407 = 4*4*4 + 0*0*0 + 7*7*7


import java.util.Scanner;

public class ArmstrongNum{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number which you want to check whether that is armstrong or not: ");
        int n = in.nextInt();
        int a = n, r=0, s=0;
       
        while(a!=0){
            r = a%10;
            a = a/10;
            s = s + r*r*r;
        }
        if(s==n){
            System.out.println("Number "+n+" is an armstrong number.");
        }else{
            System.out.println("Number "+n+" is not an armstrong number.");
        }   
    }
}


output

Enter a number which you want to check whether that is armstrong or not:
407
Number 407 is an armstrong number.

2 comments:

  1. Hi Sanjay,
    Thanks for sharing these programs...all the programs are really help full for interviews....I guess just a small enhancement is required in Armstrong number prog.
    Ex. What if the number is of 4 digit number like 1634 or 8208... in that case it should be 1 to the power 4+6 to the power 4+3 to the power 4+4 to the power 4= 1634. This is also an Armstrong number. So basically it depends on number of digits available in entered number.

    Thanks,
    Preetam

    ReplyDelete