C Unhappy Number Program

Beginner
6 min read
Updated: Nov 2026
3 programs

What Is an Unhappy Number?

A positive integer is an unhappy number when repeatedly replacing it with the sum of the squares of its digits never reaches 1. Every unhappy number ends in the same loop. It is the opposite of a happy number.

Remember
n is unhappy  <=>  digit-square chain never reaches 1

Every unhappy chain falls into this cycle:
  4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4

Example: 2
  2^2 = 4
  4^2 = 16
  1^2 + 6^2 = 37 ... and so on, back to 4
nChain (short)Result
1already 1Happy
22 → 4 → 16 → … → 4Unhappy
33 → 9 → 81 → … → 4Unhappy
1919 → 82 → 68 → 100 → 1Happy

How to Check an Unhappy Number in C

Because every unhappy chain passes through 4, you can stop as soon as the value is 1 or 4. No visited array is needed.

  1. Reject n <= 0; the definition uses positive integers.
  2. Write a helper that returns the sum of the squares of the digits of n.
  3. Loop while (n != 1 && n != 4), replacing n with its digit-square sum.
  4. If the loop stopped at 4, the number is unhappy. If it stopped at 1, it is happy.
  5. Compile with gcc file.c -std=c11 -o out and run.
MethodExtra memoryIdea
Stop at 1 or 4O(1)Every unhappy chain contains 4
Visited arraySmall arrayStop when a value repeats
Floyd tortoise and hareO(1)Two speeds meet inside a cycle

Pseudocode

Pseudocode
read n (positive)

while n != 1 and n != 4:
    n = sum of squares of the digits of n

if n == 4: unhappy
else:      happy (n == 1)

Cheat Sheet

Quick facts for the unhappy-number drill.

TopicDetail
DefinitionDigit-square chain does not reach 1
Cycle4, 16, 37, 58, 89, 145, 42, 20
Stop testn == 1 (happy) or n == 4 (unhappy)
Unhappy up to 202 3 4 5 6 8 9 11 12 14 15 16 17 18 20
Happy up to 201 7 10 13 19
Input rulePositive integers only

Worked Walkthrough — n = 20

Follow 20 until the test n != 1 && n != 4 fails.

Calculation
start: n = 20

1) 2^2 + 0^2 = 4        n = 4
   test: n == 4 -> stop

n ended at 4  =>  20 is an unhappy number

Compare 19:
   19 -> 82 -> 68 -> 100 -> 1   =>  happy

C Examples

Compile with gcc file.c -std=c11 -o out. See Happy Number for the same chain with a cycle detector.

Example 1 — Check One Number

Stop the chain at 1 or 4, then report the result.

C
#include <stdio.h>
      
      static int digit_square_sum(int n) {
          int sum = 0;
          while (n > 0) {
              int d = n % 10;
              sum += d * d;
              n /= 10;
          }
          return sum;
      }
      
      static int is_unhappy(int n) {
          while (n != 1 && n != 4) {
              n = digit_square_sum(n);
          }
          return n == 4;
      }
      
      int main(void) {
          int n;
      
          printf("Enter a positive integer: ");
          if (scanf("%d", &n) != 1 || n <= 0) {
              printf("Invalid input\n");
              return 1;
          }
      
          if (is_unhappy(n)) {
              printf("%d is an unhappy number\n", n);
          } else {
              printf("%d is a happy number\n", n);
          }
          return 0;
      }

How It Works

  1. Validate. Only positive integers are allowed.
  2. Digit-square helper. Peels digits with % 10 and /= 10.
  3. Loop until 1 or 4. Every unhappy chain reaches 4 and every happy chain reaches 1.
  4. Report. n == 4 means unhappy.

Example 2 — Print the Cycle for n = 2

Show the full chain until 4 appears for the second time.

C
#include <stdio.h>
      
      static int digit_square_sum(int n) {
          int sum = 0;
          while (n > 0) {
              int d = n % 10;
              sum += d * d;
              n /= 10;
          }
          return sum;
      }
      
      int main(void) {
          int n = 2;
          int visits_of_4 = 0;
      
          printf("%d", n);
          while (n != 1) {
              n = digit_square_sum(n);
              printf(" -> %d", n);
              if (n == 4 && ++visits_of_4 == 2) {
                  break;
              }
          }
          printf("\n");
          return 0;
      }

How It Works

  1. Start printing at 2. The chain then follows digit squares.
  2. First 4. The counter becomes 1; the loop keeps going.
  3. Around the cycle. 16, 37, 58, 89, 145, 42, 20 follow in order.
  4. Second 4. The counter reaches 2, which proves the loop, so we break.

Example 3 — List Unhappy Numbers from 1 to 20

Reuse the check inside a loop to list every unhappy number in a range.

C
#include <stdio.h>
      
      static int digit_square_sum(int n) {
          int sum = 0;
          while (n > 0) {
              int d = n % 10;
              sum += d * d;
              n /= 10;
          }
          return sum;
      }
      
      static int is_unhappy(int n) {
          while (n != 1 && n != 4) {
              n = digit_square_sum(n);
          }
          return n == 4;
      }
      
      int main(void) {
          printf("Unhappy numbers from 1 to 20:\n");
          for (int i = 1; i <= 20; i++) {
              if (is_unhappy(i)) {
                  printf("%d ", i);
              }
          }
          printf("\n");
          return 0;
      }

How It Works

  1. Loop 1 to 20. Each value is tested on its own.
  2. Happy values are skipped. 1, 7, 10, 13, and 19 end at 1.
  3. Unhappy values print. They all end at 4.
  4. Count. 15 of the 20 values are unhappy.

Edge Cases & Pitfalls

Check these before using the 1-or-4 shortcut.

input

Zero and negatives

With n <= 0 the digit loop never runs and the chain is meaningless. Reject these inputs first.

loop

Loop on the wrong stop value

Testing only n != 1 loops forever on unhappy numbers. Include n != 4 or a visited check.

overflow

Large inputs

Digit-square sums are small (at most 81 per digit), so only the very first int input needs a range check.

cycle

Starting inside the cycle

Inputs like 4, 16, or 145 are unhappy; 4 stops immediately and the others reach it quickly.

Performance Notes

ApproachTimeExtra memory
Stop at 1 or 4O(k log n)O(1)
Visited arrayO(k log n)Small fixed array
Floyd cycle detectionO(k log n)O(1)

Here k is the number of chain steps, which stays small (below about 20 for typical inputs). Each step costs one pass over the digits of the current value.

Key Takeaways

  • Definition: the digit-square chain does not reach 1.
  • Cycle: all unhappy numbers end in 4, 16, 37, 58, 89, 145, 42, 20.
  • Shortcut: stop at 1 (happy) or 4 (unhappy).
  • Input: use positive integers only.

One line: keep summing digit squares; if you land on 4, the number is unhappy.

Frequently Asked Questions

A positive integer whose digit-square chain never reaches 1. It eventually enters the cycle 4, 16, 37, 58, 89, 145, 42, 20.
Every unhappy chain enters that single 8-number cycle, and 4 is part of it. Reaching 4 therefore proves the number is unhappy.
No. 1 is already the target, so it is happy.
2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17, 18, 20, and so on.
The algorithm is the same. You only report the opposite result: unhappy when the chain ends at 4, happy when it ends at 1.
No. Because the cycle is known, comparing against 4 uses constant memory.

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.

8 people found this page helpful