C Language In this problem you have to write a program that prints all the happy
ID: 3794124 • Letter: C
Question
C Language
In this problem you have to write a program that prints all the happy numbers that are less than or equal to 1000. Here's what these numbers look like: A list of these numbers can be found online and you should use such a list to check the correctness of your program. Your program, however, should compute the numbers from the definition; it should not merely print a pre-computed list. What is a happy number? Unlike the Fibonacci numbers, happy numbers don't have a recurrence formula that gives the next happy number as a function of previous elements of the sequence. Instead, we have a criterion to tell whether positive integer n is happy or sad. It goes like this. Start with n and compute the sum of the squares of its digits. (For example, if n = 13, the sum of the squares of its digits is 1^2 + 3^2 = 10.) Repeat the computation on the number you got until the result is either 1 or 4. In the former case n is happy; in the latter case n is sad. Since 1^2 + 0^2 = 1, both 13 and 10 are happy numbers. It's easy to see that all powers of 10 are happy numbers. Note that unlike the Collets sequences mentioned in the slides, the sequences produced by the above process are known to always include either 1 or 4, but not both. Hence we are justified in defining happy numbers the way we did. Also note that the function you wrote for Problem A can be easily modified to return the sum of the squares of the digits of a positive integer instead of printing the digits. Call this modified function happy Sum and let it take an integer argument. Your program should also contain a main function that calls a function named is Happy on all the integers between 1 and 1000. Function is Happy iterates the computation of the sum of the digit squares until either 1 or 4 is obtained. It returns 1 (true) in the former case and 0 (false) in the latter case. Function main should print all the numbers for which is Happy returns 1.Explanation / Answer
CODE:
#include<stdio.h>
#include<conio.h>
int isHappy(int);
void main()
{
int i,check=0;
for(i=1;i<=1000;i++)
{
check = isHappy(i);
if(check == 1)
{
printf("%d ",i);
}
}
getch();
}
int isHappy(num)
{
int sum=0 , n , x , i;
n=num;
while(n>0)
{
x=n%10;
sum+=x*x;
n=n/10;
}
if(sum == 1)
{
return 1;
}
else if(sum == 4)
{
return 0;
}
else
{
isHappy(sum);
}
}
Drop a comment if any specific statement is not understandable!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.