Articles

C++ program to check Happy number

C++ program to check Happy number


In this chapter of C++ program tutorial out task is: 

  • write a c++ program to check whether a number is happy or not using function

Program to check Happy numbers in c++

Below is the program to check happy numbers in c++ or not using if statement and loop.

/*  Program Name: To check whether a number is happy or not
    Program Author: Sayantan Bose
*/

#include<iostream>
using namespace std;
//For calculating the sum of square of the digits
int check(int n){
 int r = 0, sum = 0;
 while(n > 0){
 r = n%10;
 sum = sum + (r*r);
 n = n/10;
 }
 return sum;
 }
 //For checking if the number is happy or not
 void solve(int n)
 {
     int new_n = n;
 while(new_n != 1 && new_n != 4){
 new_n = check(new_n);
 }
 if(new_n == 1)
cout<<n<<" is a happy number";
 else
    if(new_n==4)
 cout<<n<<" is not a happy number";
 }
 //Main function
 int main()
 {
 int n;
 cout<<"Enter the number";
 cin>>n;
 solve(n);
 return 0;
 }

OUTPUT

Enter the number 
82
82 is a happy number
Or
Enter the number 
3
3 is not a happy number
 
EXPLANATION :
In the above program to check happy numbers in c++ or not using function:
  • A number is said to be Happy if and only if the sum of the square of its digits is equal to one.
  • For example: 10 is a happy number. Because when the square of its digits are added, 12+02=1, we get 1.   
  • In the method solve, we are checking if the sum of square of the digits are equal to one or not.
  • In the method, check we are calculating the sum of square of the digits and then returning it to method solve for comparing.
  • In the main method the input is passed on to the solve method for the operation.
  • If the sum turns out to be 1, its a happy number else not.

You can see the above code execution and output in codeblocks IDE:

program to check happy numbers in c++

 


CPP Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Sayantan Bose
- šŸ”­ Iā€™m currently working on DS Algo skills - šŸŒ± Iā€™m currently learning web develeopement - šŸ‘Æ Iā€™m looking to collaborate with Oppia - šŸ“« Reach me at https://www.linkedin.com/in/sayantan-bose-14134a1a6/ - šŸ˜„ Pronouns: his/him
Page Views :    Published Date : Jan 15,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!