Write a Program to print All Armstrong numbers between 1 to 1000
This Java program prints all the Armstrong numbers between 1 to 1000. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
- The program starts by declaring and initializing the integer variables i and arm to 1. It then prints a message to the console indicating that it is going to print all the Armstrong numbers between 1 and 1000.
- The program then enters a while loop that runs until i is less than 1000. Within the loop, the program calls the armstrong() method with the current value of i as its argument, and stores the result in the arm variable.
- The armstrong() method calculates the sum of the cube of each digit of the input number using a while loop. Once the calculation is complete, the method returns the result.
- The program then checks if the value of arm is equal to the current value of i. If it is, the program prints the current value of i to the console.
- Finally, the program increments the value of i by 1 and the while loop repeats until i is no longer less than 1000.
Source Code
class All_Armstrong
{
public static void main(String arg[])
{
int i=1,arm;
System.out.println("Armstrong Numbers Between 1 to 1000");
while(i<1000)
{
arm=armstrong(i);
if(arm==i)
System.out.println(i);
i++;
}
}
static int armstrong(int num)
{
int x,a=0;
while(num!=0)
{
x=num%10;
a=a+(x*x*x);
num/=10 ;
}
return a;
}
}
Output
Armstrong Numbers Between 1 to 1000
1
153
370
371
407