HAPPY NUMBER PROGRAM IN C
In this example, you will learn a program to check whether entered number is a happy number or not.
Happy Number:
In number theory, a happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit.
Lets consider one example!
Suppose we want to check whether 19 is happy number or not.
19 =>
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² =1
And here the sum of squares of digits ends up with 1. Thus, 19 is happy number.
Program :
//Program to check whether given number is happy number
#include <stdio.h>
int isHappy(int);
int main( )
{
int num, result;
printf("Enter any number:");
scanf("%d",&num);
result=num;
while(result != 1 && result !=4)
{
result = isHapppy(result);
}
if(result==1)
{
printf("%d is a happy number",num);
}
else if(result==4)
{
printf("%d is not a happy number",num);
}
return 0;
}
int isHappy (int num)
{
int rem, sum=0;
while(num>0)
{
rem=num%10;
sum=sum+(rem*rem);
num=num/10;
}
return sum;
}
#include <stdio.h>
int isHappy(int);
int main( )
{
int num, result;
printf("Enter any number:");
scanf("%d",&num);
result=num;
while(result != 1 && result !=4)
{
result = isHapppy(result);
}
if(result==1)
{
printf("%d is a happy number",num);
}
else if(result==4)
{
printf("%d is not a happy number",num);
}
return 0;
}
int isHappy (int num)
{
int rem, sum=0;
while(num>0)
{
rem=num%10;
sum=sum+(rem*rem);
num=num/10;
}
return sum;
}
Output:
Enter any number:19
19 is a happy number
Enter a number:79
79 is not a happy number
19 is a happy number
Enter a number:79
79 is not a happy number
So that's it ! Just try this code by your own. If you have any doubts then feel free to drop a comment . I'll be happy to answer your questions .
Keep coding....
Comments
Post a Comment