Armstrong Number in JAVA Program Using For Loop

โšก Smart Summary

Armstrong numbers equal the sum of their own digits raised to the power of the digit count, and the two Java programs below check a single value and list every Armstrong number below one thousand.

  • ๐Ÿ”˜ Definition: For an n-digit number, each digit is raised to the power n and the results are added together.
  • โ˜‘๏ธ Worked Example: 370 qualifies because 3ยณ plus 7ยณ plus 0ยณ returns 370 exactly.
  • โœ… Digit Extraction: The modulo operator peels off the last digit and integer division shortens the number each pass.
  • ๐Ÿงช Two Programs: One tests a hardcoded value of 153, the other loops through every number from 0 to 999.
  • ๐Ÿ› ๏ธ Known Limit: Cubing each digit only works for three-digit values, so wider ranges need the power of n.
  • ๐Ÿ“Š Complexity: Both programs run in O(d) time per number and use O(1) extra memory.

Armstrong number in Java program using a for loop

What is Armstrong Number?

In an Armstrong Number, the sum of power of individual digits is equal to number itself.

In other words the following equation will hold true

xy..z = xn + yn+.....+ zn

n is number of digits in number

For example this is a 3 digit Armstrong number

370 = 33 + 73 + 03
 = 27 + 343 + 0
 = 370

Examples of Armstrong Numbers

0, 1, 4, 5, 9, 153, 371, 407, 8208, etc.

Every single-digit value from 0 to 9 satisfies the rule trivially, because a one-digit number raised to the power one returns itself. The complete set of three-digit Armstrong numbers is 153, 370, 371 and 407, while 1634, 8208 and 9474 are the four-digit members. Mathematicians also call these values narcissistic numbers, since each one reproduces itself from its own digits.

Letโ€™s write this in a program:

How the Armstrong Number Algorithm Works

Before reading the code, it helps to see the arithmetic that both programs repeat. The check needs only three operations: peel off the last digit, raise it to the required power, and shorten the number by one place.

  1. Copy the input into a working variable so the original value survives for the final comparison.
  2. Take the last digit with the modulo operator, digit = tempNumber % 10.
  3. Raise that digit to the power of the digit count and add it to a running total.
  4. Drop the last digit with integer division, tempNumber /= 10.
  5. Repeat until the working variable reaches 0, then compare the running total against the original number.

Running those steps over 153 produces the trace below. Every value in the table is printed by the first program, so the output can be matched line by line while learning the loop.

Pass tempNumber digit digitCubeSum
1 153 3 27
2 15 5 152
3 1 1 153
Exit 0 153 equals 153, so 153 is an Armstrong Number

One important limitation. Both programs multiply the digit by itself three times, which is the correct power only while the input has exactly three digits. The general rule raises each digit to the power n, where n is the digit count, so a four-digit value such as 8208 needs a fourth power and would be missed by cube-based code. Counting the digits first and raising each one to that power is what turns the routine into a general test.

With the arithmetic clear, the first program applies it to a single hardcoded value.

Java Program to check whether a number is Armstrong Number

The class below stores the candidate in inputArmstrongNumber and prints the working variables on every pass, which makes the Java loop easy to follow in a console.

//ChecktempNumber is Armstrong or not using while loop
package com.guru99;
 
public class ArmstrongNumber {
	public static void main(String[] args) {
		 int inputArmstrongNumber = 153; //Input number to check armstrong  
		 int tempNumber, digit, digitCubeSum = 0;
	       tempNumber = inputArmstrongNumber;
	        while (tempNumber != 0)
	        {
	        	/* On each iteration, remainder is powered by thetempNumber of digits n
	        	 */
	            System.out.println("Current Number is "+tempNumber);
	            digit =tempNumber % 10;
				System.out.println("Current Digit is "+digit);
	            //sum of cubes of each digits is equal to thetempNumber itself
	            digitCubeSum = digitCubeSum + digit*digit*digit;
				System.out.println("Current digitCubeSum is "+digitCubeSum);
	            tempNumber /= 10;
	        }
	        //check giventempNumber and digitCubeSum is equal to or not 
	        if(digitCubeSum == inputArmstrongNumber)
	            System.out.println(inputArmstrongNumber + " is an Armstrong Number");
	        else
	            System.out.println(inputArmstrongNumber + " is not an Armstrong Number");
	}
}

Compile and run the class from the project root. Because the file declares package com.guru99, it must sit in a matching com/guru99 folder, or the runtime reports a class-not-found error. Changing the value on the inputArmstrongNumber line is all that is needed to test another candidate.

Output

Current Number is 153
Current Digit is 3
Current digitCubeSum is 27
Current Number is 15
Current Digit is 5
Current digitCubeSum is 152
Current Number is 1
Current Digit is 1
Current digitCubeSum is 153
153 is an Armstrong Number

Checking one value at a time is useful for tracing, but the same logic scales to a whole range by wrapping it in an outer loop.

Java Program to Print Armstrong numbers from 0 to 999

The second version keeps the identical inner while loop and adds a for loop that walks the range. Note that digitCubeSum is reset to 0 at the top of every pass, which is the detail most beginners forget.

//ChecktempNumber is Armstrong or not using while loop
package com.guru99;
public class ArmstrongNumber {
    public static void main(String[] args) {
        int tempNumber, digit, digitCubeSum;
        for (int inputArmstrongNumber = 0; inputArmstrongNumber < 1000; inputArmstrongNumber++) {
            tempNumber = inputArmstrongNumber;
            digitCubeSum = 0;
            while (tempNumber != 0) {
                /* On each iteration, remainder is powered by thetempNumber of digits n
                 */
                digit = tempNumber % 10;
                //sum of cubes of each digits is equal to thetempNumber itself
                digitCubeSum = digitCubeSum + digit * digit * digit;
                tempNumber /= 10;
            }
            //check giventempNumber and digitCubeSum is equal to or not 
            if (digitCubeSum == inputArmstrongNumber)
                System.out.println(inputArmstrongNumber + " is an Armstrong Number");
        }
    }
}

Output

0 is an Armstrong Number
1 is an Armstrong Number
153 is an Armstrong Number
370 is an Armstrong Number
371 is an Armstrong Number
407 is an Armstrong Number

The listing stops at 1 rather than continuing to 9 because the cube of a single digit only matches the digit itself for 0 and 1. Raising each digit to the power of the digit count instead would return all ten single-digit values, which is the same generalisation described earlier.

Both listings are short enough to benchmark, so the cost of the approach is worth stating explicitly.

Time and Space Complexity of the Armstrong Number Program

The inner loop divides the working variable by 10 on every pass, so it runs once per digit rather than once per unit of the number. That makes the single-value check extremely cheap, and it stays cheap as the input grows.

Program Time complexity Space complexity
Check one number O(d), where d is the digit count O(1)
Scan a range of N numbers O(N × d) O(1)

Because d equals log10(number) rounded up, the single check is effectively logarithmic in the value being tested. Only three int variables are ever allocated, and no array or collection is created, which is why the space cost stays constant no matter how large the range becomes.

Two practical notes follow from this. First, the range scan is dominated by N, so printing Armstrong numbers up to a million costs roughly a thousand times more than printing them up to a thousand. Second, an int overflows above 2,147,483,647, so a search across very large ranges needs long for both the candidate and the running sum. The same digit-extraction pattern appears in many beginner exercises, including the prime number check, the Fibonacci series program and array drills such as bubble sort and insertion sort.

FAQs

Yes. Cubing each digit gives 27 plus 343 plus 1, which adds up to 371, so the value reproduces itself. The range program above prints it alongside 153, 370 and 407.

The name reflects the property itself: the number is built entirely from its own digits, so it appears to admire its own reflection. Both terms describe the same rule, and the digit-power sum is sometimes called a pluperfect digital invariant.

There are three: 1634, 8208 and 9474. Each digit is raised to the fourth power because the value has four digits. Cube-based code cannot detect them, which is why the exponent must follow the digit count.

A perfect number equals the sum of its proper divisors, so 6 qualifies through 1 plus 2 plus 3. An Armstrong number equals the sum of its digit powers. The two definitions share no arithmetic and rarely overlap.

Math.pow() returns a double, so a cast back to int is required and rounding errors become possible. For a fixed cube, digit*digit*digit is faster and exact. Math.pow() earns its place only when the exponent varies with the digit count.

Yes. A helper method can take the working value, add the powered last digit to an accumulator and call itself with the number divided by 10. It reads well, though the loop version avoids the extra stack frames.

Modern assistants can produce a pass-by-pass trace, restate the loop in plain language and suggest edge cases such as 0 or a negative input. Verify the trace against real console output, because generated walkthroughs occasionally skip an iteration.

GitHub Copilot usually completes the loop from the method name alone, but it often hardcodes the cube. State the digit count requirement in the prompt, then compile and test the suggestion before trusting it.

Summarize this post with: