Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Iteration Solutions in C++

I am writing a code in the following function(detectHappy) that will check whether a number is a happy number or not, for 10 cycles (iterations) only. My function should :

-Find the sum of the digits of the number.

-Check the result obtained in point 1. If it is 1, assign value 1 to the variable 'finalNumber', else again execute point 1, till the number obtained is 1 or till the number of cycle increases to 10.

-Assign the iteration value to the variable 'cycle_no'.

The code I have attempted to write compiles but does not give the correct results (e.g number 6 generates the value 32765 after 10 cycles instead of the expected 145. I am now short of ideas and I will be grateful for any assistance. Thank you in advance.


/*Question : Write your code to find whether the number is a happy number or not (for max 10 cycles).

int number : The number to be determined whether it is happy or not

int finalNumber : Store the resultant value in this variable

int cycle_no : Store the number of iterations done to determine whether the 'number' is happy or not */

void detectHappy(int number, int &finalNumber, int &cycle_no) {

//Write your solution code below this line

int sum = 0;
int i = 1;

    sum += (number%10)*(number % 10);
    number /=10;

    if (sum == 1){

        finalNumber = 1;


    else {

        number = sum;


    cycle_no = ++i;


while (i < 10);




  • B00B00 Member Posts: 115 ✭✭✭

    Isn't line 7 supposed to be a sum of digits? You just raise the last digit by power of 2.
    Line 8 is useless because number gets overwritten in line 20.

Sign In or Register to comment.