Armstrong Number in Java


Q. Write a Java program for Armstrong Number

import java.util.Scanner;

public class ArmstrongNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read the number from the user
        System.out.print("Enter a number: ");
        int originalNumber = scanner.nextInt();
        int number = originalNumber;
        int result = 0;
        int digits = 0;

        // Count number of digits
        int temp = number;
        while (temp != 0) {
            temp /= 10;
            digits++;
        }

        // Calculate sum of powers of digits
        while (number != 0) {
            int digit = number % 10;
            result += Math.pow(digit, digits);
            number /= 10;
        }

        // Check if Armstrong number
        if (result == originalNumber) {
            System.out.println(originalNumber + " is an Armstrong number.");
        } else {
            System.out.println(originalNumber + " is NOT an Armstrong number.");
        }

        scanner.close();
    }
}

Q. Write an algorithm for Armstrong Number

1. Start
2. Read an integer and store it in originalNumber
3. Set number = originalNumber, result = 0, and digits = 0
4. Count number of digits in originalNumber using a loop
5. Set number = originalNumber again
6. Repeat while number ≠ 0:
    a. Extract last digit: digit = number % 10 
    b. Add Math.pow(digit, digits) to result
    c. Remove last digit: number = number / 10
7. If result == originalNumber, print "Armstrong number"
8. Else, print "Not an Armstrong number"
9. End
 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.