Home » C Programming » Happy number program in C

Happy number program in C

What is a Happy Number?
A Happy Number is a number that will eventually reach 1 when replaced by the sum of the squares of each digit repeatedly. If it loops endlessly in a cycle (other than 1), it’s called an Unhappy Number.

Example:

  • Start with 19
    1² + 9² = 1 + 81 = 82
    8² + 2² = 64 + 4 = 68
    6² + 8² = 36 + 64 = 100
    1² + 0² + 0² = 1 → Happy Number!

📌 Steps to Check a Happy Number in C

  1. Take input from the user.
  2. Find sum of squares of each digit.
  3. Repeat the process until the number becomes 1 (Happy) or loops endlessly (Unhappy).
  4. Display result to the user.
#include<stdio.h>
#include<conio.h>
void main(){
	int f,n,d,sq,temp,ans=0;
	clrscr();
	printf("Enter your number ");
	scanf("%d",&n);
	f=n;
	do{
		while(n!=0){
			d=n%10;
			sq=d*d;
			ans=ans+sq;
			n=n/10;

		}
		temp=ans;
		n=temp;
		ans=0;

		}while(temp>=9);

	if(temp==1){
		printf("The number %d is happy number",f);


	}
	else{
		printf("The number %d is not happy number",f);



	}
	getch();

}

📥 Sample Input and Output

Example 1:

Enter a number: 19  
19 is a Happy Number.

Example 2:

Enter a number: 4  
4 is not a Happy Number.


Leave a comment

Your email address will not be published. Required fields are marked *