Here’s a Java program to check whether a given number is an Armstrong number or not:
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 originalNum = num;
int sum = 0;
while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, 3);
num /= 10;
}
if (originalNum == sum) {
System.out.println(originalNum + " is an Armstrong number");
} else {
System.out.println(originalNum + " is not an Armstrong number");
}
}
}
In this program, we first import the Scanner
class from the java.util
package to read input from the user.
We then prompt the user to enter a number using the System.out.print()
function and read the input using the nextInt()
function of the Scanner
class.
Next, we declare three integer variables originalNum
, sum
, and digit
. We initialize originalNum
to the entered number and sum
to 0.
We then use a while
loop to calculate the sum of cubes of digits of the entered number and store the result in the sum
variable.
Finally, we compare the original number with the calculated sum to determine whether it is an Armstrong number or not, and display the result using the System.out.println()
function.
When you run this program and enter a number, the output will be:
Enter a number: 153
153 is an Armstrong number
If you enter a non-Armstrong number like 123, the output will be:
Enter a number: 123
123 is not an Armstrong number
This program is a basic example of how to check if a given number is an Armstrong number or not using Java.