+ 1

Having some trouble figuring this out. Help break it down

var x = 125; var sum = 0; while (x > 0) { sum += x % 10; x = (x - x % 10) / 10; } document.write(sum)

15th Feb 2018, 12:01 AM
Briaה‎
2 Respostas
+ 3
Alright, so, I'll break it down for you. The first two lines are used to declare two variables, x and sum, which are used as reference to some value throughout your code, with it being 125 and 0 respectively. In the next line, it declares a while loop, and sets it to keep on looping until x is not less than 0. Next, within the while loop, it sets the variable sum to equal to the result of x modulo 10. A modulo operator is used to get the remainder of the division of the two operands, with the first case in the while loop resulting in 5 (125 ÷ 10 = 12 with a remainder of 5). Next, it sets the value of x to equal to the result of the initial value of x being subtracted to the modulo of x and 10, then dividing that by 10 (replacing x with its value, the equation then becomes (125 - 125 % 10) ÷ 10, resulting in 12). Finally, once the loop had run enough times for x to not be greater than 0, it then prints the value of the variable sum. Hope this helped!
15th Feb 2018, 12:24 AM
Faisal
Faisal - avatar
+ 3
What I do if I don't understand code is build in more output, like this: var x = 125; var sum = 0; while (x > 0) { sum += x % 10; document.write("sum = " + sum + "<br>"); x = (x - x % 10) / 10; document.write("x = " + x + "<br>") } document.write(sum)
15th Feb 2018, 5:10 AM
Paul
Paul - avatar