0

Could you please explain the solution of this loop-exercise? (JS)

i found an exercise on codestepbystep (https://www.codestepbystep.com/problem/view/javascript/loops/loopMystery3) and I don't get this let total = 24; for (let number = 1; number <= (total - (total % 2) / 2); number++) { total = total - number; console.log(total + " " + number); } and the solution is: 23 1 21 2 18 3 14 4 9 5 3 6 But why? Could you explain it? (total - (total % 2) / 2) gives 24, that's clear... but i'm stucked.

22nd Aug 2020, 11:24 AM
Gabor
Gabor  - avatar
1 Antwort
+ 2
Every loop has three important part. Those are: Initialization; Conditions; Incrementation/Decrementation As long as your condition is true it print total and number. Your console.log has instructions to print not only total as well number with spaces. So the output is like that. Now the explanation of output. Your condition is "number <= (total - (total%2)/2)". As long as your condition is true loop will continue to represent the output. For first, 1 <= (24 - (24%2)/2) 1 <= 24 //which is true So it print: total = total - number = 24 - 1 = 23 number = 1 Then, number = 1 + 1 = 2 2nd status: total = total - num = 23 - 2 number = 2 so on, . . Last two status: 9 5: 5 <= (9 -(9%2)/2) //true 3 6: 6 <= (3 -(3%2)/2) //false Terminated; I hope you understand. The % is a modulus operator which gave you the value of reminder of any divisional operation.
22nd Aug 2020, 11:56 AM
Bits!