Program 18 : HAPPY
NUMBER
__________________________________________________________
_____
import java.util.Scanner;
public class HappyNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
while (number != 1 && number != 4) {
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit * digit;
number /= 10;
}
number = sum;
}
if (number == 1) {
System.out.println("Happy number.");
} else {
System.out.println("Unhappy number.");
}
}
}
ALGORITHM
_____________________________________________
Step 1: Input the integer n.
Step 2: Calculate the sum of the squares of the
digits of n.
Step 3: Check if the sum equals 1.
If true, output that n is a Happy number.
Else, repeat Steps 2 and 3 with the new sum.
Step 4: If a repeating cycle is detected, output that
n is an Unhappy number.
Step 5: End the process
OUTPUT
_____________________________________________
Variable Table
_____________________________________________