📅  最后修改于: 2020-12-17 05:04:56             🧑  作者: Mango
在某些情况下,您需要多次执行一个代码块。通常,语句是按顺序执行的:函数的第一个语句首先执行,然后第二个执行,依此类推。
编程语言提供了各种控制结构,允许更复杂的执行路径。
循环语句使我们可以多次执行一个语句或一组语句,以下是大多数编程语言中循环语句的概述-
C++编程语言提供了以下类型的循环来处理循环需求。
Sr.No | Loop Type & Description |
---|---|
1 | while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
2 | for loop
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
3 | do…while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop body. |
4 | nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop. |
循环控制语句从其正常顺序更改执行。当执行离开作用域时,在该作用域中创建的所有自动对象都将被销毁。
C++支持以下控制语句。
Sr.No | Control Statement & Description |
---|---|
1 | break statement
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. |
2 | continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
3 | goto statement
Transfers control to the labeled statement. Though it is not advised to use goto statement in your program. |
如果条件永远不会为假,则循环将变为无限循环。传统上, for循环用于此目的。由于不需要形成“ for”循环的三个表达式,因此可以通过将条件表达式保留为空来进行无限循环。
#include
using namespace std;
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
当条件表达式不存在时,假定它为真。您可能有一个初始化和增量表达式,但是C++程序员通常使用’for(;;)’构造来表示一个无限循环。
注意-您可以通过按Ctrl + C键终止无限循环。