Java code for Armstrong number. In the world of computer programming and number theory, Armstrong’s number is a fascinating concept for both beginners and experienced programmers. In this article we will write a Java program that can identify Armstrong numbers.
Table of Contents
Armstrong Number
An Armstrong Number is a number that is equal to the sum of its digits each raised to the power of the number of digits in the number.
For example-153 is an armstrong number because 1^3 + 5^3 + 3^3 = 153
Java Program for Armstrong Number
Let’s write a Java code for Armstrong Number.
import java.util.Scanner;
public class Armstrong {
public static boolean isArmstrong(int number){
int temp,noOfDigits=0,sum=0;
temp=number;
while(temp>0){
noOfDigits++;
temp/=10;
}
temp=noOfDigits;
while (temp>0){
int digit=temp%10;
sum+=Math.pow(digit,noOfDigits);
temp/=10;
}
return sum==noOfDigits;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number ");
int number = sc.nextInt();
if(isArmstrong(number)){
System.out.println(number+" is an Armstrong Number");
}
else{
System.out.println(number+" is not an Armstrong Number");
}
}
}
Output
In the Above Java Program
- Inside the main method using Scanner class program captures the user’s input and calls the isArmstrong method to check if the entered number meets the criteria of the armstrong number.
- isArmstrong method performs the code logic. It calculates the number of digits in the number and than calculates the sum of digits of the number raised to the power of the number of digits in the number. It then compares this sum with the original number to determine if the given number is Armstrong’s number.
Writing a Java program to check Armstrong numbers is an excellent way to enhance understanding of loops, conditional operations, and mathematical operations in Java.
Happy Coding & Learning
3 thoughts on “Java Code for Armstrong Number”