Home »
C++ Programs
C++ program to check if the number is happy or not using class
Submitted by Shubh Pachori, on October 08, 2022
Problem statement
Given a number, we have to check whether it is happy number or not using the class and object approach.
Example:
Input:
Enter Number : 97
Output:
It is a Happy Number!
C++ code to check if the number is happy or not using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Happy {
// private data member
private:
int number;
// public member functions
public:
// getNumber() function to insert number
void getNumber() {
cout << "Enter Number : ";
cin >> number;
}
// isHappy() function to check if the number
// is happy is or not
void isHappy() {
// initialising int type variables to perform operations
int sum, remain;
// while loop to check the number
while (sum != 1 && sum != 4) {
sum = 0;
// while loop to reverse the number
while (number) {
remain = number % 10;
sum = sum + (remain * remain);
number = number / 10;
}
number = sum;
}
if (sum == 1) {
cout << "It is a Happy Number!" << endl;
} else if (sum == 4) {
cout << "It is not a Happy Number!" << endl;
}
}
};
int main() {
// create an object
Happy H;
// calling getNumber() function to
// insert the number
H.getNumber();
// calling isHappy() function to check the
// number if it is a happy number
H.isHappy();
return 0;
}
Output
Enter Number : 97
It is a Happy Number!
Explanation
In the above code, we have created a class Happy, one int type data member number to store the number, and public member functions getNumber() and isHappy() to store and check the given integer number is a happy number or not.
In the main() function, we are creating an object H of class Happy, reading an integer number by the user using the getNumber() function, and finally calling the isHappy() member function to check the given integer number. The isHappy() function contains the logic to given check the number and printing the result.
C++ Class and Object Programs (Set 2) »