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
#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;
}
Comments
Leave a comment