1 minute read

C++基础语法,包含C++循环语句for, while, do-while

1. for循环

for (int i = 5; i < 0; i--)
    cout << "i=" << i <<endl;

阶乘运算:

```C++ formore.cpp #include 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; } ```

执行结果:

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

2. while循环

while循环是没有初始化和更新部分的for循环,只有测试条件和循环体。 循环的指导原则:

  • 指定循环终止的条件
  • 在首次测试之前初始化条件
  • 在条件被再次测试之前更新条件

示例代码:

// while.cpp 
#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;
}

执行结果:

Enter your name: wizzie
w : 119
i : 105
z : 122
z : 122
i : 105
e : 101

2.1. 类型别名

  1. 使用预处理器#define BYTE char
  2. 使用关键字typedef,例如typedef char * byte_pointer;

3. do while循环

不同于前两种循环,他是出口条件循环。首先执行循环体,然后判断测试表达式。

4. 基于范围的for循环(C++11新增)

对数组或者容器类(例如vector, array)的每个元素执行相同的操作。For example:

double prices[3] = {2.33, 4122.2, 321.33};
for (double x : prices)
    std::cout << x <<std::endl;

5. 嵌套循环

for (int row = 0; row < 4; row++) {
    for (int col = 0; col < 5; ++col)
        cout << maxtemps[row][col] << "\t";
    cout << endl;
}

5.1. 二维数组

int btus[3][2] =
{
    {23, 31},
    {23, 532},
    {31243, 4231}
};

Leave a comment