In the following example, we will check whether the number 19 is an Armstrong number or not.
Example
Java Compiler
import java.lang.Math;
public class myClass
{
public static void main(String[] args)
{
int num =19;
int copyNum = num;
int digits =0;
int remainder =0;
int total =0;
// find number of digits in num variablewhile(copyNum !=0)
{
digits++;
copyNum = copyNum /10;
}
copyNum = num;
// slice the numbers from last digitswhile(copyNum !=0)
{
remainder = copyNum %10;
total += (int) Math.pow(remainder, digits);
copyNum = copyNum /10;
}
// resultif(num == total)
System.out.format("%d is an armstrong number", num);
elseSystem.out.format("%d is not an armstrong number", num);
}
}
Output
19 is not an armstrong number
Armstrong Numbers between the Given Range
In the following example, we will find all the Armstrong numbers between 1 and 200.
Example
Java Compiler
import java.lang.Math;
public class myClass
{
public static void main(String[] args)
{
int start =1;
int end =200;
int flag =0;
System.out.format("Armstrong numbers between %d and %d:\n", start, end);
for(start=start; start<=end; start++)
{
// find the number of digits in start variableint copyNum = start;
int total =0;
int digits =0;
int remainder =0;
while(copyNum !=0)
{
digits++;
copyNum = copyNum /10;
}
copyNum = start;
// slice the start variable from last digitwhile(copyNum !=0)
{
remainder = copyNum %10;
total += (int) Math.pow(remainder, digits);
copyNum = copyNum /10;
}
// resultif((start == total) && (start !=0))
{
flag =1;
System.out.print(start +" ");
}
}
if(flag ==0)
System.out.println("There is no armstrong numbers");
}
}
Output
Armstrong numbers between 1 and 200:
1 2 3 4 5 6 7 8 9 153
Check Armstrong Number for any Given Number
In the following example, we will find whether the user entered number is an Armstrong number or not.
Example
Java Compiler
import java.util.Scanner;
public class myClass
{
public static void main(String[] args)
{
Scanner reader =new Scanner(System.in);
System.out.print("Enter a (int) number: ");
int num = reader.nextInt();
int copyNum = num;
int digits =0;
int remainder =0;
int total =0;
// find number of digits in num variablewhile(copyNum !=0)
{
digits++;
copyNum = copyNum /10;
}
copyNum = num;
// slice the numbers from last digitswhile(copyNum !=0)
{
remainder = copyNum %10;
total += (int) Math.pow(remainder, digits);
copyNum = copyNum /10;
}
// resultif(num == total)
System.out.format("%d is an armstrong number", num);
elseSystem.out.format("%d is not an armstrong number", num);
}
}
Output
Enter a (int) number: 153
153 is an armstrong number
Reminder
Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.
We are working to cover every Single Concept in Java.