# Magic Number ISC 2009 Theory

A magic number is a number in which the eventual sum of the digits of the number is equal to 1.

For example, 172.
1 + 7 + 2 = 10.
1 + 0 = 1.
Thus, 172 is a magic number.

Design a class Magic to check if a given number is a magic number. Some of the members of the class are given below:

Class name: Magic
Data members:
n: stores the number.
Member functions:
Magic(): constructor to assign 0 to n.
void getNum(int num): to assign the parameter value ‘num’ to the number ‘n’.
int sumOfDigits(int): returns the sum of the digits of the number.
void isMagic(): checks if the given number is a magic number by calling the funciton sumOfDigits(int) and displays appropriate message.

Specify the class Magic by giving details of the constructor, void getNum(int), int sumOfDigits(int) and void isMagic(). You need not write the main() function.

``````class Magic{
private int n;
public Magic(){
n = 0;
}
public void getNum(int num){
n = num;
}
public int sumOfDigits(int num){
if(num < 10)
return num;
else
return num % 10 + sumOfDigits(num / 10);
}
public void isMagic(){
int result = n;
while(result >= 10)
result = sumOfDigits(result);
if(result == 1)
System.out.println(n + " is a magic number.");
else
System.out.println(n + " is not a magic number.");
}
}``````

This site uses Akismet to reduce spam. Learn how your comment data is processed.