__Question:__

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

**Example:**

$latex 28 = ( 2 )^2 + ( 8 )^2 = 4 + 64 = 68$

$latex 68 = ( 6 )^2 + ( 8 )^2 = 36 + 64 = 100$

$latex 100 = ( 1 )^2 + ( 0 )^2 + ( 0 )^2= 1 + 0 + 0 = 1$

Hence, 28 is a happy number.

**Example:** $latex 12 = ( 1 )^2 + ( 2 )^2 = 1 + 4 = 5$

Hence, 12 is not a happy number.

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

**Class name : Happy**

**Data members/instance variable :**

n : stores the number

**Member functions :**

**Happy( )** : constructor to assign 0 to n

**void getnum(int nn)** : to assign the parameter value to the number n = nn

**int sum_sq_digits(int x)** : returns the sum of the square of the digits of the number x, using the **recursive technique**

**void ishappy( )** : checks if the given number is a happy number by calling the function sum_sq_digits(int) and displays an appropriate message

Specify the class Happy giving details of the **constructor( ), void getnum(int), int sum_sq_digits(int)** and **void ishappy( )**. Also define a **main( )** function to create an object and call the methods to check for happy number.

__Solution:__

/** * The class Happy checks if a given number is a happy number or not. * @author : www.javaforschool.com * @Program Type : BlueJ Program - Java * @Question Year : ISC 2012 Question 10 */ import java.io.*; class Happy { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n; Happy() { n=0; } void getnum(int nn) { n=nn; } int sum_sq_digits(int x) { if(x==0) return 0; else { int d=x%10; return (d*d+ sum_sq_digits(x/10)); } } void ishappy() { int a=sum_sq_digits(n); while(a>9) { a=sum_sq_digits(a); } if(a==1) System.out.print(n+" is a Happy Number"); else System.out.print(n+" is Not a Happy Number"); } public static void main(String args[])throws IOException { Happy ob=new Happy(); System.out.print("Enter any number: "); int b=Integer.parseInt(br.readLine()); ob.getnum(b); ob.ishappy(); } }

__Output:__

Enter any number: 28

28 is a Happy Number

Enter any number: 12

12 is not a Happy Number

Enter any number: 68

68 is a Happy Number

7 is a happy number ..Your program does not support 7 as happy number.

Thanks Midhun. It is Corrected now. There was a small typo error. It should be:

int a=sum_sq_digits(n);instead ofint a=n;inside the functionvoid ishappy().Hello master,

7 is a happy number .Your program does not support 7 as a happy number …………any way good effort..

Corrected. There was a small typo error. It should be:

int a=sum_sq_digits(n);instead ofint a=n;inside the functionvoid ishappy().Thanks for pointing this out.

Best helping programmes:-):-)