Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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:

Flowchart: Display the first 10 catlan numbers
Flowchart: Display the first 10 catlan numbers
Flowchart: Display the first 10 catlan numbers

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?