๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

WAP to print all Armstrong numbers between 1 to 10,000 in Java  


What is Armstrong Number ?
  • An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of the n-th power of its digits, where n is the number of digits.
  • Example: 153 is an Armstrong number because:
    13+53+33=153
Logical Steps:
  • Iterate numbers from 1 to 10,000.
      Use a loop from 1 to 10,000 to check each number.
  • Calculate the number of digits for each number.
    • Count digits using a while loop.
  • Calculate the sum of digits raised to the power of the number of digits.
    • Use a for loop to compute the power manually (or we can also use Math.pow()).
  • Check if the sum is equal to the original number.
    • If it matches, print the number as an Armstrong number.
Programs:
  • Below is the simple program:
    public class ArmstrongNumberList
    {
        public static void main(String[] args)
        {
            System.out.println("Armstrong numbers between 1 and 10,000 are:");
    
            for (int no = 1; no <= 10000; no++)
            {
                int originalNumber = no;
                int sum = 0;
    
                // Calculate the number of digits
                int temp = no;
                int digits = 0;
                while (temp != 0)
                {
                    digits++;
                    temp = temp / 10;
                }
    
                int currentNumber = no;
                while (currentNumber != 0)
                {
                    int rem = currentNumber % 10;
                    int power = 1;
    
                    // Calculate rem^digits using a basic loop
                    for (int i = 0; i < digits; i++)
                    {
                        power = power * rem;
                    }
    
                    sum = sum + power;
                    currentNumber = currentNumber / 10;
                }
    
                if (sum == originalNumber)
                {
                    System.out.println(originalNumber);
                }
            }
        }
    }
    Output:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    153
    370
    371
    407
    1634
    8208
    9474
Program Explanation