C++ 学习之旅(6)——循环loop
C++中最为常用的三种循环:for 循环、while 循环和 do-while 循环,直接上代码:
for循环
for ( init; condition; increment ) { statement(s); }
- init 会首先被执行,且只会执行一次。这一步允许您声明并初始化任何循环控制变量。您也可以不在这里写任何语句,只要有一个分号出现即可。
- 接下来,会判断 condition。如果为真,则执行循环主体。如果为假,则不执行循环主体,且控制流会跳转到紧接着 for 循环的下一条语句。
- 在执行完 for 循环主体后,控制流会跳回上面的 increment 语句。该语句允许您更新循环控制变量。该语句可以留空,只要在条件后有一个分号出现即可。
- 条件再次被判断。如果为真,则执行循环,这个过程会不断重复(循环主体,然后增加步值,再然后重新判断条件)。在条件变为假时,for 循环终止。
#include <iostream> using namespace std; void Log(const char* message) { cout << message << endl; } int main() { for (int i = 0; i < 5; i++) { Log("Hello world!"); } cin.get(); }
这样就会打印 “Hello world!” 五次,而如果留空 init 和 increment ,就可以改写如下,功能不变:
#include <iostream> using namespace std; void Log(const char* message) { cout << message << endl; } int main() { int i = 0; // init for (; i < 5;) { Log("Hello world!"); i++; // increment } cin.get(); }
如果三个位置都留空,for(;;),就是无限循环。
while循环
#include <iostream> using namespace std; void Log(const char* message) { cout << message << endl; } int main() { int i = 0; while (i < 5) { Log("Hello world!"); i++; } cin.get(); }
do-while循环
#include <iostream> using namespace std; //#include "../header/Log.h" void Log(const char* message) { cout << message << endl; } int main() { int i = 0; do { Log("Hello world!"); i++; } while (i < 5); cin.get(); }
它与while循环的区别就是,条件为false的时候while循环不会执行,而do-while循环会执行:
#include <iostream> using namespace std; int main() { while (false) { cout << "while"; } cout << "======" << endl; do { cout << "do-while"; } while (false); cin.get(); }
输出为:
====== do-while
下一篇:
算法:数据流中的中位数