IT Developer

Nested for Loops in Java

Chapter 10

Nested for Loops in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Happy Number


8. Write a program to determine if an entered number is a Happy Number. A happy number is defined by the following process:


Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number is equal to 1.
For example, 19 is a happy number, as per the following calculation:
12 + 92 = 82,
82 + 22 = 68,
62 + 82 = 100,
12 + 02 + 02 = 1

Java Program : Check a Happy Number

import java.util.Scanner;

 

public class HappyNumber

{

    public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in);

 

        System.out.println("Enter a positive number:");

        int num = sc.nextInt();

 

        int original = num;

        int sum = 0;

 

        while (num != 1 && num != 4)   // 4 indicates cycle (not happy)

        {

            sum = 0;

 

            while (num > 0)

            {

                int digit = num % 10;

                sum += digit * digit;

                num = num / 10;

            }

 

            num = sum;

        }

 

        if (num == 1)

            System.out.println(original + " is a Happy Number.");

        else

            System.out.println(original + " is not a Happy Number.");

 

        sc.close();

    }

}

Output

Sample Output 1 : 
Enter a positive number:
19
19 is a Happy Number.

Sample Output 2 : 
Enter a positive number:
21
21 is not a Happy Number.

📝 Explanation

How the Program Works

  1. Take input number.
  2. Replace the number with the sum of squares of its digits.
  3. Repeat the process.
  4. If it becomes 1 → Happy Number.
  5. If it reaches 4 → Not Happy Number (cycle detection trick).

Example

Input:

19

Process:

1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1

Output:

19 is a Happy Number.

🎯 Why We Use num != 1 && num != 4

All non-happy numbers eventually fall into this cycle:

4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4

So checking for 4 avoids infinite loop.