Armstrong Number in Java


An Armstrong number is the one whose value is equal to the sum of the cubes of its digits. Armstrong Number is a positive number if it is equal to the sum of cubes of its digits is called Armstrong number and if its sum is not equal to the number then its not a Armstrong number using if else statements. The if statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets. Armstrong Number Program is very popular in java.

  Examples:
    153 => (1*1*1)+(5*5*5)+(3*3*3) = 153 is Armstrong Number
    453 => (4*4*4)+(5*5*5)+(3*3*3) = 216 is Not Armstrong Number

Source Code

import java.util.Scanner;
 
public class ArmstrongNumber {
    //Write a program to check whether the given 3 digit number is armstrong or not
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter 3 Digit Number : ");
        int number = in.nextInt();//123
        int temp = number;//123
        int digit1, digit2, digit3;
 
        digit3=temp%10;//3
        temp=temp/10;//12
 
        digit2=temp%10;//2
        temp=temp/10;//1
 
        digit1=temp%10;//1
        int result=(digit1 * digit1 * digit1)+( digit2 * digit2 * digit2)+(digit3 * digit3 * digit3);
 
        if(number==result){
            System.out.println(number + " is armstrong Number");
        }else{
            System.out.println(number + " is not an armstrong Number");
        }
 
 
    }
}
 

Output

Enter 3 Digit Number : 371
371 is armstrong Number
Enter 3 Digit Number : 634
634 is not an armstrong Number
To download raw file Click Here

Basic Programs