3.8 Iteration

0 阅读1分钟

1. Exam Points

  • Iterations:
    • REPEAT x TIMES
    • REPEAT UNTIL(EXPRESSION)
  • Nested iterations
  • Use natural language to describe an algorithm with iterations.
  • Use of iterations:
    • Select the right algorithm for a given problem.
    • Predict result or output of given code segments.
    • Compare two iteration algorithms.
    • Represent iterations using flow charts.

2. Knowledge Points

(1) Iteration

  • Iteration is a repeating portion of an algorithm.
  • Iteration repeats a specified number of times or until a given stopping condition is met.
  • Iteration constructs (构造/结构)
    • repeat n times
      • Syntax
        image.png image.png
      • Example
        image.png
    • repeat until(exit condition)
      • Syntax
        image.png image.png
      • Example
        image.png
  • In REPEAT UNTIL(condition) iteration, an infinite loop occurs when the ending condition will never evaluate to true.
    • Example:
      image.png
  • In REPEAT UNTIL(condition) iteration, if the conditional evaluates to true initially, the loop body is not executed at all, due to the condition being checked before the loop.
  • An iteration can be nested within another, you can nest any of the following loop inside another loop.
    • repeat n times
    • repeat until(condition)
  • Example of nested iteration:
    image.png image.png
  • Note: Remember to update the loop control variable to avoid infinite loops.

3. Exercises