முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 5 · பாடம் 1 இன் 4பாடத்திட்டத்தில் 17/32~10 min
தொகுதி பாடங்கள் (1/4)

சுழல்கள்: மற்றும் நேரம்

Loops let you repeat a block of code. JavaScript has three classic forms: for, while, do…while. Use the first one when you know (or can compute) the number of iterations, the other two when you just need an exit condition.

Classic for

Three parts separated by ;: initialization, continuation condition, step.

JS
for (let i = 0; i < 4; i++) {
  console.log(i); // 0, 1, 2, 3
}

Equivalent in while style:

JS
let i = 0;
while (i < 4) {
  console.log(i);
  i++;
}

while

Checks the condition before each iteration.

JS
let n = 10;
while (n > 0) {
  n = Math.floor(n / 2);
}
n; // 0

If the condition is already false at the first round, the body is never executed.

do…while

Checks the condition after: the body is always executed at least once.

JS
let tentativi = 0;
do {
  tentativi++;
} while (Math.random() < 0.0001); // pratica: provare almeno una volta

tentativi; // >= 1

Try it

உடற்பயிற்சி#js.m5.l1.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Define a function `sumUpTo(n)` that returns the sum 1+2+...+n (positive integer). Use a classic for.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Start total at 0, then loop i from 1 to n inclusive.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#js.m5.l1.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Define `halveUntilOne(n)` that, given a positive integer, returns how many times you need to divide n by 2 (with Math.floor) before reaching 1 or less. Use a while.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Keep a counter and divide n by 2 while n > 1.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்