PART II
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?
Syntax:
for (init-statement; condition-expression; end-expression)
statement
Example:
for (int count=0; count < 10; ++count)
std::cout << count << " ";
3. What is an off-by-one error?
One of the biggest problems that new programmers have with for loops (and other kinds of loops) is off-by-one errors. 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.