How to Write Java Program to Print Armstrong numbers from 0 to 999
Java is an object oriented language and some concepts may be new. Take breaks when needed, and go over the examples as many times as needed.
Armstrong Number in Java: A positive number is called armstrong number if it is equal to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.
//ChecktempNumber is Armstrong or not using while loop
package com.guru99;
public class ArmstrongNumber {
public static void main(String[] args) {
int tempNumber, digit, digitCubeSum;
for (int inputArmstrongNumber = 0; inputArmstrongNumber < 1000; inputArmstrongNumber++) {
tempNumber = inputArmstrongNumber;
digitCubeSum = 0;
while (tempNumber != 0) {
/* On each iteration, remainder is powered by thetempNumber of digits n */
digit = tempNumber % 10;
//sum of cubes of each digits is equal to thetempNumber itself
digitCubeSum = digitCubeSum + digit * digit * digit;
tempNumber /= 10;
}
//check giventempNumber and digitCubeSum is equal to or not
if (digitCubeSum == inputArmstrongNumber)
System.out.println(inputArmstrongNumber + " is an Armstrong Number");
}
}
}
Output:
0 is an Armstrong Number
1 is an Armstrong Number
153 is an Armstrong Number
370 is an Armstrong Number
371 is an Armstrong Number
407 is an Armstrong Number