Charles Charles - 3 years ago 178
C++ Question

Iterative solutions with C++

I have an assignment to fill in the body of the following function(detectHappy) that will check whether a number is a happy number or not, for 10 cycles
(iterations) only. I have to:

-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'.

I am not supposed to input, output or declare any additional functions. I just have to write the body of the function already declared there that will make it work on the shell offered in my course...

The programme I have attempted to write compiles but does not give the correct results. I am now short of ideas and I will be grateful for any assistance. Thank you in advance.

code:

/*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 = 0;

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


if (sum == 1){

finalNumber = 1;
break;

}

else {

number = sum;
i++;
}

cycle_no = i;


}

while (i < 10);


}

Answer Source

Get rid of the do while loop and add a for loop

int i; for (i=0; i <10; i++)

{

`Code stuff`

}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download