Programming Example
Java Program to Check Happy Number
Study this program carefully to understand the logic, output, and explanation in a structured way.
Enter a number to check if it's a Happy Number: 19
19 is a Happy Number!
import java.util.HashSet;
import java.util.Scanner;
public class HappyNumberChecker {
// Function to calculate the sum of squares of digits
public static int sumOfSquares(int number) {
int sum = 0, digit;
while (number > 0) {
digit = number % 10; // Extract the last digit
sum += digit * digit; // Add the square of the digit
number /= 10; // Remove the last digit
}
return sum;
}
// Function to check if a number is a Happy Number
public static boolean isHappyNumber(int number) {
HashSet<Integer> seenNumbers = new HashSet<>();
while (number != 1 && !seenNumbers.contains(number)) {
seenNumbers.add(number); // Track visited numbers
number = sumOfSquares(number); // Update the number
}
return number == 1; // Return true if it reaches 1
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check if it's a Happy Number: ");
int number = scanner.nextInt();
if (isHappyNumber(number)) {
System.out.println(number + " is a Happy Number!");
} else {
System.out.println(number + " is NOT a Happy Number.");
}
scanner.close();
}
}
Enter a number to check if it's a Happy Number: 20
20 is NOT a Happy Number.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.