Java program to check armstrong number

Hey guys!! Welcome to flower brackets blog. In this article let us learn java program to check armstrong number.

Java program to check armstrong number

Java program to check armstrong number

Here let’s see armstrong number in java using while loop,

Also read – Armstrong numbers between 1 to 1000

public class ArmstrongNumberDemo
{
public static void main(String[] args)
{
int num = 371, temp, remainder, output = 0;
temp = num;
      while(temp != 0)
{
remainder = temp % 10;
output += Math.pow(remainder, 3);
temp /= 10;
}

if(output == num)
{
System.out.println(num + " is an armstrong number.");
}
else
{
System.out.println(num + " is not an armstrong number.");
}
}
}

Output:

371 is an armstrong number.

In the same way above java program can be executed using for loop,

public class ArmstrongForLoop
{
public static void main(String[] args)
{
int num = 1944, input, remainder, output = 0, a = 0;
input = num;
      for(;input != 0; input /= 10, ++a);
input = num;

for(;input != 0; input /= 10)
{
remainder = input % 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.");
}
}
}

Output:

1944 is not an armstrong number.

Related Posts