2.7 while Loops

30 阅读1分钟

1. Exam Points

  • while loops
    • infinite loop: when the Boolean expression is always true.
    • If the Boolean expression is false in the beginning, the loop body is never executed.
    • Pay attention: print statements are inside or outside a loop.
    • The Boolean expression of a loop, when it will be true or false.
    • Analyze the first iteration and last iteration.
  • Note:
      1. Remember to update the loop control variable after each iteration.
      1. Find the initial value of the loop control variable.
      1. Find the last value of the loop control variable.
      1. Figure out what should be inside the loop body.
      1. Analyze the change of the loop control variable.
      1. Use a trace table when necessary.
      1. Try specific/sample value(s) if necessary.
      1. Analyze first iteration and last iteration.

2. Knowledge Points

(1) while Loops

  • Iteration/loop (迭代) is a form of repetition.
  • Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true.
    • Example:
    
    int i = 1 ;
    
    while (i < = 100) {
        System.out.println("dog") ;
        i = i + 1 ;
    }
    
    // here "cat" is printed after the while loop is executed 100 times.
    System.out.println("cat") ;
    
    • In while loops, the Boolean expression is evaluated before the loop body is executed.
    • That is, check the expression first, and then execute the loop body.
    • When the expression evaluates to true, the loop body is executed.
    • This continues until the Boolean expression evaluates to false, whereupon the iteration terminates.‌
  • An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true.
    • Example:
    int i = 1 ;
    
    // since i is never updated, it will always be 1, 
    // so i<=50 will always be true, leading to an infinite loop.
    
    while(i<=50) {
        System.out.println("dog") ;
    }
    
  • The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false.
    • Example:
    int i = 100 ;
    
    // i starts at 100, then i<=50 is false, 
    // so the loop body is never executed.
    
    while(i <= 50) {
        System.out.println("dog") ;
        i = i + 1 ;
    }
    
  • Off by one errors(差一错误) occur when the iteration statement loops one time too many or one time too few.(是一种常见的编程错误,通常由于边界条件处理不当,导致循环或计数时多算一次或少算一次。‌)
    image.png

3. Exercises