Advertisements
Advertisements
Question
A number is said to be Armstrong if the sum of cube of its digits is equal to the same number.
For example, 153 = 13 + 53 + 33
Hence, 153 is an Armstrong number.
A program using a class is designed below to check and display whether a number 'num' is an Armstrong number or not. There are some places in the program left blank marked with ?1?, ?2?, ?3? and ?4? to be filled with suitable condition/expression.
class Armstrong
{
private int num;
Armstrong(int n)
{
num = n;
}
boolean check()
(
int nm= num;
while(....... ?1? ........)
{
digit = nm % 10;
sum = sum + ......... ?2? .......;
nm = ........ ?3? .........;
}
if (sum == num)
return(true);
else
return(false)
}
void display()
{
boolean ch = check();
if (ch == ....... ?4? .......)
System.out.println("Number is Armstrong");
Else
System.out.println("Number is not Armstrong");
}
Based on the above discussion, answer the following questions:
- What will be filled in place of ?1?
- What will be filled in place of ?2?
- What will be filled in place of ?3?
- What will be filled in place of ?4?
Case Study
Solution
- nm > 0
- Mth.pow(digit, 3)
- nm / 10
- true
The complete program is as follows:
class Armstrong {
private int num;
Armstrong(int n) {
num = n;
boolean check() {
int nm = num;
while (nm > 0) {
digit = nm % 10;
sum = sum + Math.pow(digit , 3);
nm = nm / 10 ;
}
if (sum == num)
return(true);
else
return(false);
}
void display() {
boolean ch = check();
if(ch == true )
System.out.println("Number is Armstrong");
else
System.out.println("Number is not Armstrong");
}
}
}
shaalaa.com
Is there an error in this question or solution?