Working with Variable Controlled Loops

Name:

#

Code

Question

1

console.log("Loops repeat code.");

console.log("Loops repeat code.");

console.log("Loops repeat code.");

console.log("Loops repeat code.");

console.log("This is below the loop.");

Loops are used to repeat code. What part of the code can we use a loop on?

How many times should the loop repeat?

2

var count = 0;

while(count < 3) {

   console.log("Loops repeat code.");

   count = count + 1;

}

How many times will the code on left print (console.log) “Loops repeat code.”? Why do you think so?

3

  • Variable x equals 0, x = 0
  • While x is less than 2 run next line
  • Print “Hello, world!”
  • Add 1 to x, since x was equal to zero, x now equals 1, x = 1
  • While x is less than 2 run next line
  • Print “Hello, world!”
  • Add 1 to x, since x was equal to one, x now equals 2, x = 2
  • While x is less than 2 run next line

The box to the left has a loop that is explained without code. Use that information to create a code for a loop that is being described.

4.

console.log("Loops repeat code.");

console.log("Loops repeat code.");

console.log("Loops repeat code.");

console.log("Loops repeat code.");

console.log("This is below the loop.");

Rewrite the code on the left using a loop.

5

var num = 0;

while(num < 3) {

   console.log("Again.");

   console.log("And again.");

   num = num;

}

This loop is not correct, the loop would be repeated forever, it would not stop. Why? What is wrong with the loop?