Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print Armstrong number from 100 to 500

Java Code Example — Series Programs

ADVERTISEMENT

Java Program to print Armstrong number from 100 to 500

Objective

Write a Java program to find and print all Armstrong numbers between 100 and 500.

Algorithm / Approach

  1. Start a for loop with i running from 100 to 500.
  2. Inside the loop, assign i to a temporary variable temp.
  3. Initialize sum to 0.
  4. Use a while loop to extract digits from temp until it becomes 0.
  5. Extract the last digit using r = temp % 10.
  6. Cube the digit (r * r * r) and add it to sum.
  7. Remove the last digit from temp using temp = temp / 10.
  8. After the while loop, if sum == i, print the number i.
Test.java
class Test {
 public static void main(String[] a)
 {
  int temp,r,sum;
  for(int i=100; i<=500; i++) {
   temp = i;
   sum = 0;
   while(temp!=0) {
    r = temp%10;
    sum = sum+(r*r*r);
    temp = temp/10;
   }
   if(sum ==i) {
    System.out.print(i+"  ");
   }
  }  
 }
}

Expected Output

153  370  371  407

Explanation of the Program

  • An Armstrong number of 3 digits is an integer such that the sum of the cubes of its digits is equal to the number itself.
  • The outer loop iterates through the target range (100 to 500).
  • The inner while loop processes each digit of the current number mathematically without converting it to a string.
  • Because we need the original number for the final comparison, we perform the digit extraction on a copy (temp) rather than modifying i directly.

Complexity

Time Complexity O(N * log10(M)) - Where N is the range size (400) and M is the maximum value (500).
Space Complexity O(1)

Common Mistakes

  • Modifying the loop variable i directly in the while loop, causing an infinite loop because i drops to 0.
  • Forgetting to reset sum = 0 at the start of each iteration in the outer loop.
ADVERTISEMENT