Happy Number Code 

Happy Number: Replace the number by the sum of the squares of its digits, and repeat the process. At the end, if the number is equals to 1 then it is a Happy Number, or it loops endlessly in a cycle that does not include 1 (if it is not a happy number then this process will end at 4).

For example:

23 is a Happy Number

23 :> 2^2 + 3^2 = 13
13 :> 1^2 + 3^2 = 10
10 :> 1^2 + 0   = 1

As we reached to 1, 23 is a Happy Number.


42 is a UnHappy Number

42 :> 4^2 + 2^2 = 20
20 :> 2^2 + 0 = 4

As we reached to 4, 42 is a UnHappy Number.

C++ codes


#include<iostream.h>
int main()
 int num,temp,sum=0;
 cout<<"Enter a Number : ";
 cin>>num;
 while(sum!=1 && sum!=4)
 {
  sum=0;
  while(num>0)
  {
   temp=num%10;
   sum+=(temp*temp);
   num=num/10;
  }
   num=sum;
 }
 if(sum==1)
  cout<<"Happy Number";
 else
  cout<<"UnHappy Number";
 return 0;
}


OUTPUT:


(Run 1)
Enter a Number : 19
Happy Number

(Run 2)
Enter a Number : 40
UnHappy Number

Copy the codes



Helping all of you to make us happy find the Happy Number Code  for c++. how did you feel about



SUBSCRIBE to our YouTube channel, visit to: 

 

 *********************************************


 Follow code with mrinal on Instagram 



**********************************************


Follow code with mrinal on Website



**********************************************


Follow code with mrinal on Twitter



**********************************************


Follow code with mrinal on Iinkedin 



********************************************** 


 Follow code with mrinal on Facebook


******************************************


 Subscribe code with mrinal on YouTube

 
********************************************


Post a Comment

Previous Post Next Post