armstrong number in java for 4 digits code example
Example 1: Java program to print all armstrong numbers between given range
import java.util.Scanner;
public class ArmstrongNumbersGivenRange
{
public static void main(String[] args)
{
int number, startNumber, endNumber, a, rem, n, count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter starting number range: ");
startNumber = sc.nextInt();
System.out.println("Please enter ending number range: ");
endNumber = sc.nextInt();
for(a = startNumber + 1; a < endNumber; a++)
{
n = a;
number = 0;
while(n != 0)
{
rem = n % 10;
number = number + rem * rem * rem;
n = n / 10;
}
if(a == number)
{
if(count == 0)
{
System.out.println("Armstrong numbers between given range " + startNumber + " and " + endNumber + ": ");
}
System.out.print(a + " ");
count++;
}
}
if(count == 0)
{
System.out.println("Sorry!! There's no armstrong number between given range " + startNumber + " and " + endNumber);
}
sc.close();
}
}
Example 2: 4 digit armstrong number in java
public class ArmstrongNumberDemo
{
public static void main(String[] args)
{
int num = 9474, realNumber, remainder, output = 0, a = 0;
realNumber = num;
for(;realNumber != 0; realNumber /= 10, ++a);
realNumber = num;
for(;realNumber != 0; realNumber /= 10)
{
remainder = realNumber % 10;
output += Math.pow(remainder, a);
}
if(output == num)
{
System.out.println(num + " is an Armstrong number.");
}
else
{
System.out.println(num + " is not an Armstrong number.");
}
}
}