Write a java Program which accept a number from user and check whether it is Armstrong or not. | EasyCoding45

Write a Java program that accepts a number from the user and checks whether it is Armstrong or not.


An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or pluperfect number) is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because:

13+53+33=1+125+27=153.

Here's a simple Java program to check if a given number is an Armstrong number or not:


Program :(Write a Java program that accepts a number from the user and checks whether it is Armstrong or not.)

import java.util.Scanner; public class ArmstrongNumber { // Function to calculate the number of digits in a given number static int countDigits(int num) { int count = 0; while (num != 0) { num /= 10; count++; } return count; } // Function to check if a number is an Armstrong number static boolean isArmstrong(int num) { int originalNum = num; int result = 0; int n = countDigits(num); while (num != 0) { int digit = num % 10; result += Math.pow(digit, n); num /= 10; } return result == originalNum; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number to check if it's an Armstrong 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(); } }

This program defines two functions: countDigits to count the number of digits in a given number and isArmstrong to check if a number is an Armstrong number. The main method takes user input, calls the isArmstrong function, and prints the result.

Output :

https://easycoding45.blogspot.com/2023/11/write-java-program-which-accept-number.html

Comments