Program to Check if a Number is an Armstrong Number in Java

Armstrong Number

An Armstrong number (or narcissistic 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 and 9474 are Armstrong numbers.

We will explore a method to check if a given number is an Armstrong number using Java programming.

Method: Using a while Loop

We extract each digit, raise it to the power of the number of digits, and sum them up to check the Armstrong condition.

import java.util.Scanner;

public class Main {
    public static boolean isArmstrong(int num) {
        int originalNum = num, sum = 0, digit, n = 0, temp = num;
        
        // Count the number of digits
        while (temp != 0) {
            temp /= 10;
            n++;
        }
        
        temp = num;
        
        // Calculate the sum of digits raised to the power of n
        while (temp != 0) {
            digit = temp % 10;
            sum += Math.pow(digit, n);
            temp /= 10;
        }
        
        return (sum == num);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        
        if (isArmstrong(num))
            System.out.println(num + " is an Armstrong number");
        else
            System.out.println(num + " is not an Armstrong number");
        
        scanner.close();
    }
}
            

Output:

Enter a number: 153
153 is an Armstrong number
Easy aceess next quctions
Getting Started

Positive or Negative number: C C++ Java Python

Even or Odd number: C C++ Java Python

Sum of First N Natural numbers: C C++ Java Python

Sum of N natural numbers: C C++ Java Python

Sum of numbers in a given range: C C++ Java Python

Greatest of two numbers: C C++ Java Python

Greatest of the Three numbers: C C++ Java Python

Leap year or not: C C++ Java Python

Prime number: C C++ Java Python

Prime number within a given range: C C++ Java Python

Sum of digits of a number: C C++ Java Python

Reverse of a number: C C++ Java Python

Palindrome number: C C++ Java Python

Armstrong number: C C++ Java Python

Armstrong number in a given range: C C++ Java Python

Harshad number: C C++ Java Python

Abundant number: C C++ Java Python

Friendly pair: C C++ Java Python