GENERATING THREE
DIGIT ARMSTRONG NUMBERS
AIM: To write a program in Java to generate three-digit
Armstrong Numbers.
Note: Armstrong numbers are three digit numbers whose sum
of cubes of the individual digits of the number is equal to the number itself. For Example, 153 is an Armstrong number.
(153 = 13 + 53
+ 33 = 1 + 125 + 27 = 153, an Armstrong number)
ALGORITHM:
- Declare
two variables n, m and sum of type int in method main()
- Use
a for loop with an index variable i that starts with value
100 and end with value 999 for the following:
- Take the current value of i as the next number to be verified. This is done by assigning the current
value of i to n
- Initialize the value of sum to 0 (sum=0)
- Repeat the following until n>0
i.
Separate the right most digit of n by applying modulus operator on n (n%10)
and store it in m
ii.
Add the cubic value of m to sum
iii.
Reduce the value of n by 10 (n/10).
Let n has the remaining digits
except the right most digit.
- Check
whether the value of i (i.e.,
the current three digit number) and the value of sum are equal. If so,
print the number as the next Armstrong number.
PROGRAM:
public class ArmstrongNos {
public static void
main(String[] args) {
int n, m, sum;
System.out.println("Three Digit Armstrong numbers are : ");
for(int i=100; i<=999;
i++)
{
n = i;
sum = 0;
while(n!=0)
{
m = n%10;
sum = sum + (int)
Math.pow(m, 3);
n = n/10;
}
if(sum == i)
System.out.print(i+
" ");
}
System.out.println("");
}
}
Sample
Run: