Java Program to Check Armstrong Number
An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.
In this tutorial, we will create a Java program to check whether a given number is an Armstrong number.
By the end of this guide, you will understand digit manipulation and power calculations in Java.
Concept Overview
To check an Armstrong number, we extract each digit, raise it to the power of total digits, and sum them.
If the sum equals the original number, it is an Armstrong number.
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 num = sc.nextInt();
int original = num;
int sum = 0;
int digits = String.valueOf(num).length();
while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, digits);
num = num / 10;
}
if (sum == original) {
System.out.println(original + " is an Armstrong Number");
} else {
System.out.println(original + " is not an Armstrong Number");
}
}
}
Output
Enter a number: 153
153 is an Armstrong Number
Detailed Explanation
The program starts by reading input from the user using the Scanner class.
The original number is stored for final comparison.
The number of digits is calculated using String.valueOf(num).length().
Each digit is extracted using the modulus operator (%).
Each digit is raised to the power of total digits using Math.pow().
The sum of all powered digits is compared with the original number.
Example Walkthrough
Let us consider 153.
Calculation: 1³ + 5³ + 3³ = 153.
Since the result equals the original number, it is an Armstrong number.
Applications
Armstrong number logic is used in number theory problems, coding challenges, and algorithm practice.
Advantages of This Approach
This program helps beginners understand loops, digit extraction, and mathematical functions.
It introduces the use of built-in functions like Math.pow().
Limitations
The program may face precision issues with Math.pow() for large numbers.
Improvements You Can Make
You can replace Math.pow() with manual multiplication for better control.
You can also optimize digit counting without converting to a string.
This Java program strengthens logical thinking and understanding of mathematical programming concepts.
Codecrown