How come the program outputs 123? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

How come the program outputs 123?

var i=1; do { document.write(i + "<br />"); i++; } while(Math.floor(i/2) == 1);

11th Jul 2019, 7:34 PM
eMBee
eMBee - avatar
2 Answers
+ 48
Well, here we have a do while loop (works at least once) and a floor function that rounds the result of division down. Do statement executes before evaluating the while condition. Step 1 var is 1, it gets printed out and increased by 1. Do statement is done. Step 2 while var is 2 it is divided by 2 and the result equals 1. Hence while is true the loop continues. Step 3 var equals 3. 3 divided by 2 equals 1.5 but it is still 1 rounded down. The result gets printed out and i becomes 4. Finally 4 divided by 2 is 2. The loop breaks.
11th Jul 2019, 7:55 PM
🇺🇦 Vitya 🇺🇦
🇺🇦 Vitya 🇺🇦 - avatar
+ 5
Memorize these three words: Run. Through. It. i is 1. It's printed, then incremented. 2 / 2 is 1, then i is printed; then incremented again, to 3, 3 / 2 is 1.5, and 1.5's floor is 1. i is printed as 3, then incremented. At this point i is 4, 4 / 2 is 2, and that's no good for the loop :[ TL;DR print (1) i = 2 -> 2 / 2 = 1 print (2) i = 3 -> 3 / 2 = 1(.5) print (3) i = 4 -> 4 / 2 = 2 -> break
11th Jul 2019, 7:41 PM
Airree
Airree - avatar