C++ Unhappy Number Program

Beginner
6 min read
Updated: Nov 2026
1 program

What Is an Unhappy Number?

Start with a positive integer and replace it with the sum of the squares of its digits. Repeat. If you reach 1, the number is happy. If you reach the cycle that contains 4, the number is unhappy (sometimes called sad).

Remember
Unhappy cycle:
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4

2 is unhappy (it reaches 4)
7 is happy (it reaches 1)

How to Check an Unhappy Number

  1. Require n > 0.
  2. Replace n with the sum of the squares of its digits.
  3. Stop when you see 1 (happy) or 4 (unhappy). Every unhappy chain hits 4.
  4. A set of seen values also works, and it detects any cycle.

C++ Program

Classify one positive integer as happy or unhappy.

C++
#include <iostream>

int squareDigits(int n) {
    int sum = 0;
    while (n > 0) {
        int d = n % 10;
        sum += d * d;
        n /= 10;
    }
    return sum;
}

bool isUnhappy(int n) {
    while (n != 1 && n != 4)
        n = squareDigits(n);
    return n == 4;
}

int main() {
    int n;
    std::cout << "Enter a positive integer: ";
    std::cin >> n;

    if (n <= 0) {
        std::cout << "Enter a positive integer.\n";
        return 0;
    }
    if (isUnhappy(n))
        std::cout << n << " is unhappy\n";
    else
        std::cout << n << " is happy\n";
    return 0;
}

Frequently Asked Questions

A positive integer whose digit-square chain reaches the cycle containing 4, instead of reaching 1.
Yes. 4 maps to 16, and the chain comes back to 4.
Yes, for this process. A positive integer either reaches 1 or enters the 4-cycle.
Every unhappy chain hits 4, so you do not need to store the whole cycle.
This page starts from positive integers. 0 stays 0, so it is not happy and is not in the 4-cycle.

Next: Harshad Number

Check whether a number is divisible by the sum of its digits.

Harshad number tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful