1. What can we do with the while statement?
Execute a block of code repeatedly until a condition is met.
2. What value needs the statement in the brackets evaluate to in order for the loop to continue?
True.
3. What is an infinite loop?
A loop that never stops executing because the condition is never met (expression is always true).
4. What is an iteration?
An execution of the loop code block.
1. When is it a good idea to use a for statement (do a for loop) instead of the while loop we learned previously?
The for statement (also called a for loop ) is ideal when we know exactly how many times we need to iterate, because it lets us easily define, initialize, and change the value of loop variables after each iteration.
2. How would you write a for-loop in code?
for (init-statement; condition-expression; end-expression)
statement
-
The init-statement is evaluated. Typically, the init-statement consists of variable definitions and initialization. This statement is only evaluated once, when the loop is first executed.
-
The condition-expression is evaluated. If this evaluates to false, the loop terminates immediately. If this evaluates to true, the statement is executed.
-
After the statement is executed, the end-expression is evaluated. Typically, this expression is used to increment or decrement the variables declared in the init-statement. After the end-expression has been evaluated, the loop returns to step 2.
3. What is an off-by-one error?
Off-by-one errors occur when the loop iterates one too many or one too few times. This generally happens because the wrong relational operator is used in the conditional-expression (eg. > instead of >=). These errors can be hard to track down because the compiler will not complain about them – the program will run fine, but it will produce the wrong result.