这里只是对Control structures 简要说明。
一般的, 我们的程序执行的顺序都是一个语句一个语句按照顺序执行。 但是有的时候, 我们常常需要改变程序语句执行的顺序, 好处自不必说。 这就是the control flow。
control flow 需要两种control structures, 一种是条件语句(conditionals), 一种是循环loops。
1.control structure 1: contionals:
1.1 if 条件句
#include <iostream>
using namespace std;
int main() {
int x = 6;
int y = 2;
if (x > y)
cout << "x is greater than y\n";
else if (y > x)
cout << "y is greater than x\n";
else
cout << "x and y are equal\n";
return 0;
}
1.2 switch case 语句
#include <iostream>
using namespace std;
int main() {
int x = 6;
switch (x) {
case 1:
cout<< "x is 1\n";
break;
case 2:
case 3:
cout << "x is 2 or 3";
break;
default:
cout << "x is not 1, 2, or 3";
}
return 0;
}
2.control structure 2: Loops
C++ 有三种loops: while, do while, and for
2.1 while 和do-while
#include <iostream>
using namespace std;
int main() {
int i = 0;
while(i < 10)
i = i + 1;
cout << "i is" << endl; //this program will print: i is 10
return 0;
}
注意:
do {
statement1
statement2
...
} while (conmdition)
能够保证{ }中的语句至少执行一次。
2.2for循环
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 10; i++) {
cout << i << "\n";
}
return 0;
}
This program will print values 0 through 9, each on its own line
如果计数的变量已经提前定义了, 在for 循环语句的初始化区域就不需要重新定义一个。
<pre name="code" class="cpp">#include <iostream>
using namespace std;
int main() {
int i = 0;
for( ; i < 10; i++) {
cout << i << "\n";
}
return 0;
}
for循环语句可以转换为while 语句
#include <iostream>
using namespace std;
int main() {
int i = 0;
while(i < 10) {
cout << i << "\n";
i++
}
return 0;
}
2.3 Nesed Control structures
如下例子:
#include <iostream>
using namespace std;
int main() {
int x;
int y;
if (x > y) {
cout << "x is greater than y \n";
if(x == 6)
cout << "x is equal to 6 \n";
else
cout << "x is not equal to 6 \n";
}
else
cout << "x is not greater than y\n";
return 0;
}
例如下面的nesed loop:
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
cout << j;
cout << "\n";
}
return 0;
}
This program will print four lines of 0123