Java Program to Check Armstrong Number

18
views
Java Program to Check Armstrong Number
(Last Updated On: October 31, 2018)

In this program, you’ll learn how to Check Armstrong Number

To properly understand this Program to Check Armstrong Number, you should have the knowledge of following Java programming topics:

  • Java I/o
  • Java while loop
  • Java if..else-if

let’s let’s first understand what is Armstrong numbers. A number is called Armstrong number if the following equation holds true for that number:

Armstrong Number Formula

where n denotes the number of digits in the number

What is Armstrong Number

For example, this is a 4 digit Armstrong numbers

4 Digit Armstrong Number

Program to check whether the given number is Armstrong number

public class JavaExample {

    public static void main(String[] args) {

        int num = 370, number, temp, total = 0;

        number = num;
        while (number != 0)
        {
            temp = number % 10;
            total = total + temp*temp*temp;
            number /= 10;
        }

        if(total == num)
            System.out.println(num + " is an Armstrong number");
        else
            System.out.println(num + " is not an Armstrong number");
    }
}

Output

370 is an Armstrong number
Java Program to check whether the given number is Armstrong number
follow @coderforevers on Instagram

In the above program we have used while loop, However, you can also use for loop. To use for loop replace the while loop part of the program with this code:

for( ;number!=0;number /= 10){
    temp = number % 10;
    total = total + temp*temp*temp;
}

Program to check whether the input number is Armstrong or not

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

        int num, number, temp, total = 0;
        System.out.println("Ënter 3 Digit Number");
        Scanner scanner = new Scanner(System.in);
        num = scanner.nextInt();
        scanner.close();
        number = num;

        for( ;number!=0;number /= 10)
        {
            temp = number % 10;
            total = total + temp*temp*temp;
        }

        if(total == num)
            System.out.println(num + " is an Armstrong number");
        else
            System.out.println(num + " is not an Armstrong number");
    }
}

Output

Enter 3 Digit Number
371
371 is an Armstrong number
Java Program to check whether the input number is Armstrong or not
follow @coderforevers on Instagram

Check out the related programs:

Ask your questions about how to check Armstrong num in Java and clarify your/others doubts by commenting. Documentation.

Please write to us at [email protected] to report any issue with the above content or for feedback.