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.
int i = 1 ;
while (i < = 100) {
System.out.println("dog") ;
i = i + 1 ;
}
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.
int i = 1 ;
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.
int i = 100 ;
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.(是一种常见的编程错误,通常由于边界条件处理不当,导致循环或计数时多算一次或少算一次。)
