1. Exam Points
for loop
- for loop and while loop (equivalent loop)
- for loop algorithms (ex. find sum/average)
- for loop + string manipulation
- loop condition is evaluated: number of iterations + 1
Note:
- Analyze how the loop control variable (i) changes.
- First iteration and last iteration.
- Use trace tables if necessary.
- check print statements is inside the loop or outside a loop.
2. Knowledge Points
(1) for Loops
- A
for loopis a type of iterative statement. - There are
three parts in a for loop header: the initialization, the Boolean expression, and the update.
- How a for loop is executed:
-
initialization: int i =1
-
- check the
Boolean expression: i <=5
- check the
-
- if true, execute the
loop body
- if true, execute the
-
incrementi by 1 (i++)
-
repeat steps 2 to 4until the Boolean expression evaluates to false.
-
- Execution of the for loop here:
- Execution of the for loop here:
-
- How many times i <= 5 is evaluated?
6
- How many times i <= 5 is evaluated?
-
How many times each part is executed?
- part 1 -> 1
- part 2 -> n+1
- part 3 -> n
- part 4 -> n
- A for loop can be rewritten into an equivalent while loop (and vice versa).