This C tutorial helps you understand Happy Numbers and guides you in writing a C program to verify them. Here, you will learn how to determine whether the number entered by the user is a Happy Number.
What is a Happy Number?
A happy number is defined in mathematics as a process that replaces a number with the sum of the squares of its digits. This process is repeated until the number either equals 1 (indicating a "happy" ending) or loops indefinitely in a cycle that does not contain 1 (indicating the number is not "happy").
For example, consider the number 23:
- First, we find the sum of the squares of its digits: (2^2) + (3^2) = 4 + 9 = 13
- For the resulting 13, we repeat the process: (1^2) + (3^2) = 1 + 9 = 10
- We do the same for 10: (1^2) + (0^2) = 1
In the above example, we arrive at the number 1 after three processes, indicating that 23 is a happy number. The number is not happy if the process enters a loop that does not result in a 1.
C Program to Check if a Number Is Happy
Below is the complete C program to check whether a number is a Happy Number or not:
#include<stdio.h>
int main() {
int num, digit, sum = 0;
// Prompt user for input
printf("Enter any number: ");
scanf("%d", &num);
// While the number has more than one digit, calculate the sum of squares
while(num > 0 || sum > 9) {
if(num == 0){
num = sum;
sum = 0;
}
// Get the last digit of the number
digit = num % 10;
// Add the square of the digit to sum
sum += digit * digit;
// Remove the last digit from the number
num /= 10;
}
// If the sum is 1, it's a happy number. Otherwise, it's not.
(sum == 1)? printf("It is a happy number.\n"): printf("It is not a happy number.\n");
return 0;
}
Program Output:
Here are some examples of running the program and the corresponding output:
Enter any number: 23
It is a happy number.
Enter any number: 12
It is not a happy number.