Armstrong Number in Java


This is a Java program that checks whether a given three-digit number is an Armstrong number or not. An Armstrong number is a number that is equal to the sum of its digits raised to the power of the number of digits.

The program prompts the user to input a three-digit number and then performs the following steps:

  • It stores the number in a variable called number and creates a copy of it called temp.
  • It extracts each digit from temp by using the modulo operator (%) and integer division (/), and stores them in variables called digit1, digit2, and digit3.
  • It computes the sum of the cubes of digit1, digit2, and digit3, and stores it in a variable called result.
  • It compares number to result and outputs whether or not number is an Armstrong number.

Note that this program assumes that the user enters a three-digit number, and will not work correctly if the user enters a number with a different number of digits.

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