Answer to Question #333749 in C++ for mimi

Question #333749

Happy Numbers: 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 a recursive function that checks whether

the number entered by the user is a happy number or not for 10 cycles/iterations only. The

output shown in blue colour should be shown by the function and text in yellow colour

should be displayed by the main function.


1
Expert's answer
2022-04-25T16:59:10-0400
#include <iostream>


using namespace std;


int main()
{
	int n, squareSum=0;
	cout << "Please, enter a number: ";
	cin >> n;
	int i = 0;
	int k = n;
	while (i<10)
	{
		while (k > 0)
		{
			squareSum += (k % 10)*(k % 10);
			k /= 10; 
		}
		if (squareSum == 1)
		{
			cout << n << " is happy number!";
			break;
		}
		k = squareSum;
		squareSum = 0;
		i++;
	}
	if(i==10)
		cout << n << " is not happy number!";
}



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