C++ Exercises: Check a number is a Happy or not
C++ Numbers: Exercise-16 with Solution
Write a program in C++ to check a number is a Happy or not.
Sample Solution:
C++ Code :
#include <bits/stdc++.h>
using namespace std;
int SumOfSquNum(int givno)
{
int SumOfSqr = 0;
while (givno)
{
SumOfSqr += (givno % 10) * (givno % 10);
givno /= 10;
}
return SumOfSqr;
}
bool checkHappy(int chkhn)
{
int slno, fstno;
slno = fstno = chkhn;
do
{
slno = SumOfSquNum(slno);
fstno = SumOfSquNum(SumOfSquNum(fstno));
}
while (slno != fstno);
return (slno == 1);
}
int main()
{
int hyno;
cout << "\n\n Check whether a number is Happy number or not: \n";
cout << " ---------------------------------------------------\n";
cout << " Input a number: ";
cin >> hyno;
if (checkHappy(hyno))
cout << hyno << " is a Happy number\n";
else
cout << hyno << " is not a Happy number\n";
}
Sample Output:
Check whether a number is Happy number or not: --------------------------------------------------- Input a number: 23 23 is a Happy number
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C++ to display the first 10 Catlan numbers.
Next: Write a program in C++ to find the Happy numbers between 1 to 1000.
What is the difficulty level of this exercise?