Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Happy Number (OOP)

Updated 20 Oct 2026

A happy number reaches 1 when it is repeatedly replaced by the sum of the squares of its digits. This version is written as a class Happy with a data member, a constructor and methods that each do one job, and main() creates an object and calls them.

Definition

Square each digit of the number and add the squares; repeat with the result. If the value becomes 1 the number is happy, otherwise the values go round in a loop. The number 1 is happy, while 0 and negative numbers are treated as invalid input.

  • $7$: $49$, $97$, $130$, $10$, $1$, so $7$ is happy.
  • $89$: $145$, $42$, $20$, $4$ and then the cycle $16, 37, 58, 89$ repeats, so $89$ is not happy.

Algorithm

  1. main() reads the number into num. If num is 0 or negative it prints an invalid-input message, because 0 would give 0 for ever and never reach 1.
  2. Otherwise main() creates the object ob with new Happy(num). The constructor Happy(int nn) stores the value in the data member n.
  3. ob.display() calls isHappy() and prints the result.
  4. isHappy() copies n into t and repeats while t is neither 1 nor 4:
    • t is replaced by sumSq(t).
  5. sumSq(x) returns the sum of the squares of the digits of x, using x % 10 to take a digit and x / 10 to remove it.
  6. isHappy() returns true if t ended as 1 and false if it ended as 4.

Why the loop can stop at 4. Every number that is not happy ends in the cycle $4, 16, 37, 58, 89, 145, 42, 20, 4$. Once the value reaches 4 it goes round this cycle for ever and can never reach 1, so reaching 4 proves the number is not happy.

Program

The constructor stores the number, sumSq() squares and adds the digits, isHappy() repeats until 1 or 4, and display() prints the message.

import java.util.*;

/* Class Happy checks whether a number is a happy number, i.e. repeatedly
   replacing it by the sum of the squares of its digits ends in 1. */
public class Happy
{
    int n;      // stores the number to be checked

    /* Constructor: assigns the number to the data member n.
       Parameter nn: the number to be checked. */
    Happy(int nn)
    {
        n = nn;
    }

    /* Returns the sum of the squares of the digits of the number x.
       Parameter x: the number whose digits are squared and added. */
    int sumSq(int x)
    {
        int s = 0;              // accumulates the sum of squares
        while (x > 0)
        {
            int d = x % 10;     // extracts the last digit
            s = s + d * d;      // adds the square of the digit
            x = x / 10;         // removes the last digit
        }
        return s;
    }

    /* Returns true if n is a happy number, otherwise false.
       The number is replaced by its sum of squares of digits until the value
       becomes 1 (happy) or 4 (every unhappy number reaches 4). */
    boolean isHappy()
    {
        int t = n;              // working copy so that n is not changed
        while (t != 1 && t != 4)
        {
            t = sumSq(t);       // replace by sum of squares of its digits
        }
        return t == 1;          // 1 means happy, 4 means unhappy
    }

    /* Displays whether the number n is happy or not. */
    void display()
    {
        if (isHappy())
            System.out.println(n + " is a Happy Number");
        else
            System.out.println(n + " is not a Happy Number");
    }

    /* main: reads a number, creates the object and calls display().
       Parameter args: command line arguments (not used). */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);    // reads input from the keyboard
        System.out.print("Enter a number: ");
        int num = sc.nextInt();                 // number entered by the user
        if (num <= 0)                           // 0 would never reach 1 or 4
            System.out.println("Invalid input. Enter a positive number.");
        else
        {
            Happy ob = new Happy(num);          // object of class Happy
            ob.display();
        }
    }
}

Variable description table

VariableData TypePurpose
nintData member that stores the number to be checked
nnintParameter of the constructor that carries the number into n
xintParameter of sumSq(); the number whose digits are squared and added
sintLocal variable of sumSq() that accumulates the sum of squares of the digits
dintLast digit of x in the current pass of the loop
tintWorking copy of n in isHappy() that is replaced by the sum of squares each pass
argsString[]Command line arguments of main() (not used)
scScannerReads the number typed at the keyboard in main()
numintNumber entered by the user
obHappyObject of class Happy created in main()

Sample input and output

Sample 1

Enter a number: 7
7 is a Happy Number

Sample 2

Enter a number: 89
89 is not a Happy Number

Sample 3

Enter a number: 0
Invalid input. Enter a positive number.

One value per line

Dry run

Input: num = 89, so the constructor sets n = 89 and isHappy() sets t = 89.

Passt beforeDigits squaredt aftert is 1 or 4?
18964 + 81145No
21451 + 16 + 2542No
34216 + 420No
4204 + 04Yes, loop stops

t == 1 is false, so isHappy() returns false and the program prints 89 is not a Happy Number, the same as the real run above.

Variations

  1. Range "Accept two integers m and n and display all the happy numbers between m and n."
  2. Unhappy number "Check whether a number is an unhappy number."
  3. Recursion "Write the happy number check using a recursive method."