Page 374 - computer science (868) class 11
P. 374
Program 7 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
10 = 1 + 0 = 1
Then 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: [ISC 2009]
Class name : Magic
Data Members
n : Stores the number
Member Methods
Magic() : Constructor to assign 0 to n
void getnum(int nn) : Assigns the parameter value to the number, n = nn
int Sum_of_digits(int) : Returns the sum of the digits of the number
void ismagic() : Checks if the given number is a magic number by calling the
function Sum_of_digits(int) and displays an appropriate message
Specify the class Magic by giving details of the constructor, void getnum(int), int Sum_of_
digits(int) and void ismagic(). You should write the main function to create an object and call
other functions.
1 class Magic
2 {
3 int n;
4 Magic()
5 {
6 n = 0;
7 }
8 void getnum(int nn) // parameterised input
9 {
10 n = nn;
11 }
12
13 int Sum_of_digits(int a)
14 { // base case
15 if(a == 0)
16 return 0;
17 else
18 return a%10+Sum_of_digits(a/10); // recursive call
19 }
20
372372 Touchpad Computer Science-XI

