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