Loops
Used to repeatedly run a block of code until a certain condition is met
while loop var sum = 0; var number = 1; while (number <= 50) { // -- condition sum += number; // -- body number++; // -- updater } alert("Sum = " + sum); // => Sum = 1275
What is a post test loop?
A do-while loop, as the condition is evaluated after the block has executed.
Which loop has three parts, separated by semicolons?
For loop.
So when do we use for and when while?
If the number of iterations is known use the for-loop. If you want to loop until a certain condition is met use the while-loop.
How to cause an infinite while loop?
Remove the updater ( number++).
How does a do-while loop work?
The block following do is executed first and then the condition is evaluated. If the while condition is true, the block is executed again and repeats until the condition becomes false. var sum = 0; var number = 1; do { sum += number; // -- body number++; // -- updater } while (number <= 50); // -- condition alert("Sum = " + sum); // => Sum = 1275
How do while loops work?
The condition is first evaluated. If true, the block of statements following the while statement is executed. This is repeated until the condition becomes false.
When is a do-while loop often used?
The do-while is typically used in a situation where the body of a loop contains a statement that generates a value that you want to use in your conditional expression, like this: do { // read a character from keyboard in the body } while (if ch === '0'); // => terminate loop if '0' is entered
A big difference between the do-while and while loops is....
The do-while loop is executed at least once whereas the while loop may not execute at all.
What are the three parts of a for loop?
The first is the initializer (var i = 1) which initializes the loop and is executed only once at the start. The second is a test condition (i <= 50). When a conditional expression evaluates to true, the body of the loop is executed. When false, the loop terminates. The third part is an updater (i++) which is invoked after each iteration. The updater typically increments or decrements the loop counter. var sum = 0; for (var i = 1; i <= 50; i++) { sum = sum + i; } alert("Sum = " + sum); // => Sum = 1275
In a for-loop, all three parts i.e. initializer, test condition, and updater are written together in a single line called?
The iteration statement.
What is a pretest loop?
While loop. This is known as a pre-test loop because the condition is evaluated before the block is executed.