for循环
1 2
| for (int i = 5; i < 0; i--) cout << "i=" << i <<endl;
|
阶乘运算:
formore.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include<iostream> using namespace std; const int SIZE = 16;
int main() { long long factorials[SIZE]; factorials[1] = factorials[0] = 1LL;
for (int i = 2; i < SIZE; i++) factorials[i] = i * factorials[i-1];
for (int i = 0; i < SIZE; i++) cout << i << "! = " << factorials[i] <<endl;
return 0; }
|
执行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 11! = 39916800 12! = 479001600 13! = 6227020800 14! = 87178291200 15! = 1307674368000
|
while循环
while循环是没有初始化和更新部分的for循环,只有测试条件和循环体。
循环的指导原则:
- 指定循环终止的条件
- 在首次测试之前初始化条件
- 在条件被再次测试之前更新条件
示例代码:
while.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include<iostream>
using namespace std;
const int SIZE = 20;
int main() { char name[SIZE]; cout << "Enter your name: "; cin >> name;
int i = 0; while(name[i] != '\0') { cout << name[i] << " : " << int(name[i]) <<endl; i++; } return 0; }
|
执行结果:
1 2 3 4 5 6 7
| Enter your name: wizzie w : 119 i : 105 z : 122 z : 122 i : 105 e : 101
|
类型别名
- 使用预处理器
#define BYTE char
- 使用关键字
typedef
,例如typedef char * byte_pointer;
do while循环
不同于前两种循环,他是出口条件循环
。首先执行循环体,然后判断测试表达式。
基于范围的for循环(C++11新增)
对数组或者容器类(例如vector, array)的每个元素执行相同的操作。For example:
1 2 3
| double prices[3] = {2.33, 4122.2, 321.33}; for (double x : prices) std::cout << x <<std::endl;
|
嵌套循环
1 2 3 4 5
| for (int row = 0; row < 4; row++) { for (int col = 0; col < 5; ++col) cout << maxtemps[row][col] << "\t"; cout << endl; }
|
二维数组
1 2 3 4 5 6
| int btus[3][2] = { {23, 31}, {23, 532}, {31243, 4231} };
|