ICSE Class 10 Computer Applications Question 19 of 22

Nested for loops — Question 19

Back to all questions
19
Question

Question 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

import java.util.Scanner;

public class KboatHappyNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number to check: ");
        long num = in.nextLong();
        long sum = 0;
        long n = num;
        do {
            sum = 0;
            while (n != 0) {
                int d = (int)(n % 10);
                sum += d * d;
                n /= 10;
            }
            n = sum;
        } while (sum > 6);

        if (sum == 1) {
            System.out.println(num + " is a Happy Number");
        }
        else {
            System.out.println(num + " is not a Happy Number");
        }
    }
}
Output
BlueJ output of KboatHappyNumber.java
BlueJ output of KboatHappyNumber.java
Answer