Google News
logo
Armstrong Number in Java Program
An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Here's a Java program that checks if a given number is an Armstrong Number or Not:
Program :
import java.util.Scanner;

public class ArmstrongNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = sc.nextInt();
        sc.close();

        int originalNumber = number;
        int numberOfDigits = 0;

        // Count the number of digits
        while (originalNumber != 0) {
            originalNumber /= 10;
            numberOfDigits++;
        }

        int sum = 0;
        originalNumber = number;

        // Calculate the sum of digits raised to the power of number of digits
        while (originalNumber != 0) {
            int digit = originalNumber % 10;
            sum += Math.pow(digit, numberOfDigits);
            originalNumber /= 10;
        }

        if (number == sum) {
            System.out.println(number + " is an Armstrong number.");
        } else {
            System.out.println(number + " is not an Armstrong number.");
        }
    }
}
Output :
Enter a number: 371
371 is an Armstrong number.
Enter a number: 870
870 is not an Armstrong number.
In this program, we first read a number input from the user using the Scanner class. We store the original number in a variable called originalNumber, and count the number of digits in the number using a while loop.

We then calculate the sum of digits raised to the power of number of digits using another while loop. In each iteration of the loop, we extract the last digit of the number using the modulo operator %, and add it to the sum after raising it to the power of number of digits using the Math.pow() method. We then remove the last digit from the number using integer division /.

Finally, we use an if statement to check if the original number is equal to the sum. If they are equal, we print a message indicating that the number is an Armstrong number. Otherwise, we print a message indicating that the number is not an Armstrong number.