Write a ‘java’ program to check whether given number is Armstrong or not. (Use static keyword) | EasyCoding45
Write a ‘java’ program to check whether given number is Armstrong or not. (Use static keyword).
Program : (Write a ‘java’ program to check whether given number is Armstrong or not. (Use static keyword))
import java.util.Scanner;
public class ArmstrongNumber1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
scanner.close();
}
// Function to check whether a number is Armstrong or not
private static boolean isArmstrong(int num) {
int originalNumber, remainder, result = 0, n = 0;
originalNumber = num;
// Count the number of digits
while (originalNumber != 0) {
originalNumber /= 10;
++n;
}
originalNumber = num;
// Calculate the sum of nth power of digits
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
originalNumber /= 10;
}
// Check if the result is equal to the original number
return result == num;
}
}
isArmstrong
to check whether a given number is an Armstrong number or not. The main
method takes user input, calls the isArmstrong
function, and prints the result.
Comments
Post a Comment