Answer to Question #327538 in C++ for elion

Question #327538

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-11T16:50:15-0400
#include <iostream>
using namespace std;


int sum_of_squares(int n) {
    int s = 0;
    while (n > 0) {
        int d = n % 10;
        s += d*d;
        n /= 10;
    }
    return s;
}


bool is_happy_number(int n) {
    for (int i=0; i<10; i++) {
        n = sum_of_squares(n);
        if (n == 1) {
            return true;
        }
    }
    return false;
}


int main() {
    int n;
    
    cout << "Enter a number: ";
    cin >> n;


    if (is_happy_number(n)) {
        cout << n << " is a happy number." << endl;
    }
    else {
        cout << n << " is not a happy number." << endl;
    }
    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