Javatpoint Logo
Javatpoint Logo

C program to check if the given number is Happy Number

In this program, we need to determine whether the given number is a Happy number or not by following the algorithm below:

2. Happy Number

A number is said to be happy if it yields 1 when replaced by the sum of squares of its digits repeatedly. If this process results in an endless cycle of numbers containing 4, then the number will be an unhappy number.

Let's understand by an example:

Number = 32
32+ 22 = 13
12 + 32 = 10
12 + 02 = 1

In this example, we split 32 to get the sum of squares of its digits which forms another number (13), we replace 32 by 13 to continue this cycle until result 1. We found 32 a happy number.

If the above cycle for any number results 1 then that number will be a Happy number otherwise that will be an unhappy number resulting 4, 16, 37, 58, 89, 145, 42, 20,.....

Some Happy numbers are 7, 28, 100, 320 etc.

ALGORITHM:

main()

  • STEP 1: START
  • STEP 2: SET num =82
  • STEP 3: result = num
  • STEP 4: REPEAT STEP 5 UNTIL (result!=1 && result!=4)
  • STEP 5: result = isHappyNumber(result)
  • STEP 6: if(result==1) then PRINT "Yes"
                  else
                  if(result==4) then PRINT("No")
  • STEP 7: RETURN 0
  • STEP 8: END

isHappyNumber(int num)

  • STEP 1: START
  • STEP 2: SET rem =0, sum =0
  • STEP 3: REPEAT STEP 4 to 6 UNTIL (num>0)
  • STEP 4: rem= num%10
  • STEP 5: sum = sum + (rem*rem)
  • STEP 6: num =num/10len
  • STEP 7: RETURN sum
  • STEP 8: END

PROGRAM:

In this program, integer value is predefined, user don't need to put integer value to check Happy number.

Output:

82 is a happy number
Next TopicC Programs





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA