Loops
Sometimes, we need to perform a task repeatedly. To avoid writing excessive duplicate code, we need loops.
Sometimes, the number of repetitions is not a constant, so we cannot simply duplicate the code multiple times; we must use loops.
for Statement
The structure of a for statement is as follows:
1 2 3 | |
Execution order:
e.g., reading n numbers:
1 2 3 | |
Any of the three parts of a for statement can be omitted. If the condition is omitted, it is equivalent to the condition always being true.
while Statement
The structure of a while statement is as follows:
1 2 3 | |
Execution order:
e.g., verifying the 3x+1 conjecture:
1 2 3 4 5 6 7 | |
do...while Statement
The structure of a do...while statement is as follows:
1 2 3 | |
Execution order:
The difference from the while statement is that the do...while statement executes the loop body first before checking the condition.
e.g., enumerating permutations:
1 2 3 | |
Relationship Between the Three Statements
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
These are equivalent when there is no continue statement in statement4 (see below), but the latter method is rarely used.
1 2 3 4 5 6 7 8 9 10 11 12 | |
These two methods are also equivalent when there is no continue statement in statement1.
1 2 3 4 5 6 7 | |
Both of these methods loop indefinitely. (You can use break (see below) to exit.)
It can be seen that the three statements can replace each other, but generally, the choice follows these principles:
- When there is a fixed increment step during the loop (most commonly enumeration), use the for statement;
- When only the termination condition of the loop is known, use the while statement;
- When using a while statement, if the loop body must be executed before checking the condition, use the do...while statement. This is rarely used; a common scenario is user input.
break and continue Statements
The break statement is used to exit a loop.
The continue statement is used to skip the rest of the loop body. The following example shows the use of continue in a do...while statement:
1 2 3 4 5 6 | |
Both break and continue statements can be used in the loop bodies of all three loop statements.
Generally, break and continue statements are used to make the logic of the code clearer, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用