Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
8.6k views
in Computer by (49.9k points)
closed by

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: 

28 = (2)2 + (8)2 = 4 + 64 = 68 

68 = (6)2 + (8)2 = 36 + 64 = 100 

100 = (1)2 + (0)2 + (0)2 = 1 + 0 + 0 = 1

Hence, 28 is a happy number. 

Example: 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 variables: 

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 is happy (): 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 ( s) function to create an object and call the methods to check for happy number.

1 Answer

+1 vote
by (49.0k points)
selected by
 
Best answer

class Happy 

int n, s, d; 

public Happy() { n = 0; 

void getnum (int nn) 

n = nn, 

int sum_sq_digits(int x) 

if (x > 0) 

d = x%10; 

s = s + d*d;

x = x/10; 

return (sum_sq_digits (x)); 

else { returns; 

void ishappy () 

int a;

while (n > 9) 

s = 0; 

n = sum_sq_digits(n): 

if (n== 1) 

System.out.println("Happy No.");

else System out.println("Not a Happy No."); 

}

}

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...