Answer to Question #329472 in C++ for Jack

Question #329472

A number is called a happy number, if you start with the given number

and arrive at 1 by repeating the following process (as illustrated in the below example): (a)

compute the sum of the squares of given number digits (b) if the resultant value is 1, then

the number is happy number, else execute point (a) for the newly produced number.

Note that if a number is not a happy number, there will be an endless loop to this execution.

Goal: In this question, you are required to write C++ code that checks whether the number entered by the user is a happy number or not for 10 cycles/iterations only.

Example: Assume a number 19

Number Computation Result cycle/iterations



19 1^2 + 9^2 82 1


82 8^2 + 2^2 68 2


68 6^2 + 8^2 100 3


100 1^2 + 0^2 +0^2 1 4


1
Expert's answer
2022-04-18T08:41:19-0400
#include <iostream>


int get_squares_sum(int n) {
  int result = 0;
  while (n) {
    int digit = n % 10;
    result += digit * digit;
    n /= 10;
  }
  return result;
}


int main() {
  int n;
  std::cout << "Enter a number: ";
  std::cin >> n;
  bool is_happy = false;
  for (int i = 0; i < 10; ++i) {
    n = get_squares_sum(n);
    if (n == 1) {
      is_happy = true;
      break;
    }
  }
  std::cout << "This number is " << (is_happy ? "" : "not ") << "a happy number\n";
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS