Armstrong Number in a Particular Range Example in Java
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 5When 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.