2.8 for Loops

0 阅读1分钟

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 loop is a type of iterative statement.
  • There are three parts in a for loop header: the initialization, the Boolean expression, and the update.
    image.png
  • How a for loop is executed:
    image.png
      1. initialization: int i =1
      1. check the Boolean expression: i <=5
      1. if true, execute the loop body
      1. increment i by 1 (i++)
      1. repeat steps 2 to 4 until the Boolean expression evaluates to false.
      1. Execution of the for loop here: image.png
      1. How many times i <= 5 is evaluated? 6
  • How many times each part is executed?
    image.png
    • 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). image.png

3. Exercises