Armstrong number in java

Armstrong Number Program in Java

Armstrong numbers are integers that can be expressed as the sum of the cubes of their individual digits.

For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

In this article, we will discuss the concept of Armstrong numbers and provide a Java program for checking if a given number is an Armstrong number or not. We will also delve into the logic behind the program and provide example to illustrate its functionality.

The algorithm will be:

  1. Enter and Store the Integer Input.
  2. Create a duplicate of the input for later comparison.
  3. Run a While loop construct such that it will run until the input is not reduced to 0.
  4. Extract each individual digit of the input using Modulus Operator.
  5. Perform Cumulative Sum of the Cubic Power of each digit extracted.
  6. After the loop terminates, compare the duplicate of the user input with the cumulative sum.
  7. If the result of comparison is true, the input is an Armstrong number.
  8. Print the result accordingly.
import java.util.*;

class Armstrong
{
  public static void main()
  {
    Scanner inp = new Scanner(System.in);
    System.out.print("\n Enter Number: ");
    int n = inp.nextInt();
    int a, s = 0, m = n;

    while (n != 0)   // Extracting each digits and raising them to cubic power while accumulating its sum.
    {
      a = n % 10;
      s = s + (a * a * a);
      n = n / 10;
    }

    if (s == m)          // Checking if sum is equal to original number.
      System.out.println(m + " is an Armstrong Number");
    else
      System.out.println(m + " is not an Armstrong Number");
  }
}

Output

Enter Number: 153
153 is an Armstrong Number

 Enter Number: 306
306 is not an Armstrong Number
Armstrong number in java