Write a Program to check Armstrong numbers or Not


This Java program checks whether a given number is an Armstrong number or not. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.

  • The program starts by importing the Scanner class, which allows the program to read input from the user.
  • The program then creates an instance of the Scanner class and prompts the user to enter a number. The program reads the input number using the nextInt() method of the Scanner class and stores it in the integer variable n.
  • Next, the program initializes three integer variables: rem, t, and p. The variable rem is used to store the remainder when n is divided by 10, and the variables t and p are used to store the original input number and the result of the Armstrong number calculation, respectively.
  • The program then enters a while loop that runs until n is greater than 0. Within the loop, the program calculates the cube of the remainder (rem) using the formula rem * rem * rem and adds it to the variable p. The variable n is then divided by 10 to remove the last digit.
  • Once the calculation is complete, the program checks if the value of the original input number (t) is equal to the value of the calculated result (p). If they are equal, the program prints a message indicating that the number is an Armstrong number. Otherwise, the program prints a message indicating that the number is not an Armstrong number.

Source Code

import java.util.Scanner;
public class Check_Armstrong {
	public static void main(String[] args)
	{
 
        Scanner input = new Scanner(System.in);		
        System.out.print("Enter The Number : ");
        int n = input.nextInt();
		int rem,t = n,p = 0;
		while (n > 0) 
		{
			rem = n % 10;
			p = p + (rem * rem * rem);
			n = n / 10;
		}
		if (t == p) {
			System.out.println(p+" is Armstrong Number");
		}
		else {
			System.out.println(p+" is Not an Armstrong Number");
		}
	}
}
 

Output

Enter The Number : 371
371 is Armstrong Number

Example Programs