Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.
This Infinite loops and updating the loop variable worksheet is part of the ACARA Digital Technologies Years 7–8 — Programming with Control Structures and Functions (JavaScript) journey. Print it as a booklet?
Shade in the A or B circle for each question.
Draw a line connecting each item on the left to its match on the right.
| Left column | Right column | |
|---|---|---|
| 1while (count < 5) { count++; } | Alet lives = 3; while (lives > 0) { lives--; } | |
| 2while (true) { console.log("Hi"); } | Blet n = 1; while (n > 0) { n++; } | |
| 3To make a loop stop, update the variable that the condition tests inside the loop body. | CThe loop stops because count++ changes count each time, so count < 5 eventually becomes false. | |
| 4A condition that can never become false makes the loop run forever, even if the variable is updated. | Dcount goes up, moving away from 0, so count > 0 is always true. Use count-- so it counts down to 0. | |
| 5let count = 0; while (count < 5) { console.log(count); } | EThe loop never changes count, so count < 5 stays true forever. Add count++; inside the loop body. | |
| 6let count = 10; while (count > 0) { count++; } | FAn infinite loop: the condition is always true and nothing in the body can make it false. |
Complete each line of code by filling in the missing parts.
Shade in the letter of the line that contains an error.
while (count < 5) { count++; } — A loop runs forever if nothing in its body changes the variable its condition tests. Updating count each time lets the condition become false so the loop stops.while (count < 5) { count++; }let lives = 3;
while (lives > 0) { lives--; }while (true) { console.log("Hi"); }let n = 0;
while (n < 3) { n++; }while (true) { if (n > 4) break; n++; }