Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

C++ Program to Check Happy Number

Posted in C++ Tutorial
Updated on Oct 06, 2024
By Mari Selvan
πŸ‘οΈ 175 - Views
⏳ 4 mins
πŸ’¬ 1 Comment
C++ Program to Check Happy Number

Photo Credit to CodeToFun

πŸ™‹ Introduction

In the domain of programming, certain mathematical properties and patterns are often explored. One such interesting concept is the notion of "happy numbers."

This tutorial focuses on a C++ program designed to check whether a given number is a happy number.

πŸ“„ Example

Let's delve into the C++ code that checks whether a given number is a happy number or not.

isHappyNumber.cpp
Copied
Copy To Clipboard
#include <iostream>

// Function to calculate the sum of squares of digits
int sumOfSquares(int n) {
  int sum = 0;
  while (n > 0) {
    int digit = n % 10;
    sum += digit * digit;
    n /= 10;
  }
  return sum;
}

// Function to check if a number is a happy number
bool isHappyNumber(int n) {
  int slow = n, fast = n;
  do {
    slow = sumOfSquares(slow);
    fast = sumOfSquares(sumOfSquares(fast));
  } while (slow != fast);

  return (slow == 1);
}

// Driver program
int main() {
  // Replace this value with your desired number
  int number = 19;

  // Check if the number is a happy number
  if (isHappyNumber(number)) {
    std::cout << number << " is a Happy Number." << std::endl;
  } else {
    std::cout << number << " is not a Happy Number." << std::endl;
  }

  return 0;
}

πŸ’» Testing the Program

To test the program with a different number, replace the value of number in the main function.

Output
19 is a Happy Number.

Compile and run the program to check if the number is a happy number.

🧠 How the Program Works

  1. The program defines a function sumOfSquares to calculate the sum of the squares of digits of a given number.
  2. It then defines a function isHappyNumber that checks whether a given number is a happy number using Floyd's cycle detection algorithm.
  3. The main function tests the program with a sample number (in this case, 19).

πŸ“ Between the Given Range

Let's take a look at the C++ code that checks for Happy Numbers in the specified range.

isHappy.cpp
Copied
Copy To Clipboard
#include <iostream>
#include <unordered_set>

// Function to check if a number is happy
bool isHappy(int n) {
  std::unordered_set < int > seen;
  while (n != 1 && seen.find(n) == seen.end()) {
    seen.insert(n);
    int sum = 0;
    while (n > 0) {
      int digit = n % 10;
      sum += digit * digit;
      n /= 10;
    }
    n = sum;
  }
  return n == 1;
}

// Function to print happy numbers in a range
void printHappyNumbersInRange(int start, int end) {
  std::cout << "Happy numbers in the range " << start << " to " << end << ":\n";
  for (int i = start; i <= end; ++i) {
    if (isHappy(i)) {
      std::cout << i << " ";
    }
  }
  std::cout << "\n";
}

// Driver program
int main() {
  // Set the range
  int start = 1;
  int end = 50;

  // Call the function to print happy numbers in the range
  printHappyNumbersInRange(start, end);

  return 0;
}

πŸ’» Testing the Program

The provided program is set to check for happy numbers in the range from 1 to 50. You can customize the range by changing the values of start and end in the main function.

Output
Happy numbers in the range 1 to 50:
1 7 10 13 19 23 28 31 32 44 49

Compile and run the program to see the happy numbers in the specified range.

🧠 How the Program Works

  1. The program defines a function isHappy that checks if a number is a happy number.
  2. Inside the function, it uses a set to keep track of numbers encountered during the process to avoid infinite loops.
  3. The printHappyNumbersInRange function iterates through the specified range and prints the happy numbers.

🧐 Understanding the Concept of Happy Number

A happy number is a positive integer defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle that does not include 1.

For example, let's take the number 19:

  1. 12+92 = 82
  2. 82+22 = 68
  3. 62+82 = 100
  4. 12+02+02 = 1

In this case, 19 is a happy number because the process ends with 1.

🎒 Optimizing the Program

While the provided program is effective, there are various ways to optimize and enhance it further. Consider exploring different algorithms or incorporating additional features based on your specific requirements.

Feel free to incorporate and modify this code as needed for your specific use case. Happy coding!

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mari Selvan
Mari Selvan
10 months ago

If you have any doubts regarding this article (C++ Program to Check Happy Number), please comment here. I will help you immediately.

We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy