5.1 for循环
// forloop.cpp -- introducing the for loop
#include <iostream>
int main()
{
using namespace std;
int i; // create a counter
// initialize; test ; update
for (i = 0; i < 5; i++)
cout << "C++ knows loops.\n";
cout << "C++ knows when to stop.\n";
return 0;
}
5.1.1 for循环的组成部分
1.设置初始值。
2.执行测试,看看循环是否应当继续进行。
3.执行循环操作。
4.更新用于测试的值。
for (initialization; test-expression; update-expression)
body
C++循环允许:
for (for-init-statement condition; expression)
statement
5.1.9 组合赋值运算符
5.1.12 关系表达式
5.2 while循环
while (test-condition)
body
5.2.1 for与while
for (init-expression; test-expression; update-expression)
{
statement(s)
}
init-expression;
while (test-expression)
{
statement(s)
update-expression;
}
while (test-expression)
body
for ( ;test-expression;)
body
for ( ; ; )
body
在设计循环时,请记住下面几条指导原则。
- 指定循环终止的条件。
- 在首次测试之前初始化条件。
- 在条件被再次测试之前更新条件。
5.3 do while循环
do
body
while (test-expression);
首先执行循环体,然后再判定测试表达式,决定是否应继续执行循环。false,循环终止;true,进入新一轮的执行和测试。
5.4 基于范围的for循环
double prices[5] = {4.99, 10.99, 6.87, 7.99, 8.49};
for (double x : prices)
cout << x << std::endl;
5.5.5 另一个cin.get()版本
5.6 嵌套循环和二维数组
int maxtemps[4][5];
maxtemps包含4个元素的数组,其中每个元素都是一个由5个整数组成的数组。
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 5; ++col)
cout << maxtemps[row][col] << "\t";
cout << endl;
}
5.6.1 初始化二维数组
int maxtemps[4][5] = // 2-D array
{
{96, 100, 87, 101, 105}, // values for maxtemps[0]
{96, 98, 91, 107, 104}, // values for maxtemps[1]
{97, 101, 93, 108, 107}, // values for maxtemps[2]
{98, 103, 95, 109, 108} // values for maxtemps[3]
};
5.6.2 使用二维数组
const string cities[Cities] = // array of 5 strings
{
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};