In this tutorial, we will write a C++ program to check happy number. Let us start by defining a happy number.
Happy Number
A number is said to be a happy number if it yields 1 after a few steps and each step is the sum of the squares of the digits of its results. The sum of the squares starts with the given number and till it reaches one.
Follow the diagram below:
Explanation: In the above diagram input is 19. Then the digits 1 and 9 are squared which gives the result 82. After that, the digits 8 and 2 are squared and yield the results 68 and this continues till the final result is 1. And then we can say that 19 is a happy number, if not then it is not a happy number.
Happy Number Program in C++
Question: C++ program to check whether a number is happy or not using function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <iostream> using namespace std; //Calculation int check(int num) { int rem = 0, sum = 0; while (num > 0) { rem = num % 10; sum = sum + (rem *rem); num /= 10; } return sum; } //Function to check void isHappyNumber(int num) { int result = num; while (result != 1 && result != 4) { result = check(result); } if (result == 1) cout << num << " is a happy number"; else if (result == 4) cout << num << " is NOT a happy number"; } //Drive function int main() { int num; cout << "Enter the number: "; cin >> num; isHappyNumber(num); return 0; } |
Output:
Enter the number: 15
15 is not a happy number
//Another Execution
Enter the number: 32
32 is a happy number