Armstrong Number in a Particular Range Example in Java
On this page (9sections)
Introduction
Armstrong Number In A Particular Range is a classic Java console program that demonstrates the concept with complete source code and sample output. Calculation programs apply formulas to solve geometry, statistics and numeric problems.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 3
Armstrong Number In A Particular Range Example Program
import java.util.Scanner;
public class FindArmstrongNumberInRange{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range :");
int range=in.nextInt();
int num1,num2,num3,sum,count=0;
num2=1;
while(num2<=range){
sum=0;
num3=num2;
while(num3>0){
num1=num3%10;
sum=sum+(num1*num1*num1);
num3=num3/10;
}
if(sum==num2){
System.out.println(num2+" is a Armstrong Number");
count=count+1;
}
num2++;
}
System.out.println("Total Armstrong Number Present With in that Range is "+count);
}
}
Sample Output
Enter the Range :1067
1 is a Armstrong Number
153 is a Armstrong Number
370 is a Armstrong Number
371 is a Armstrong Number
407 is a Armstrong Number
Total Armstrong Number Present With in that Range is 5
When to use
Use these formulas in homework tools, engineering calculators or anywhere repeated numeric computation is needed.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
Scannerreads typed input from the keyboard (System.in). -
A
println/printcall writes text to the console — part of the sample output below. -
int range=in.nextInt();updates a variable used in the calculation or output. -
int num1,num2,num3,sum,count=0;updates a variable used in the calculation or output. -
num2=1;updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.