第4课: 流程控制
if语句
#include <iostream>
using namespace std;
int main() {
int score = 85;
// 单分支
if (score >= 60) {
cout << "及格" << endl;
}
// 双分支
if (score >= 60) {
cout << "及格" << endl;
} else {
cout << "不及格" << endl;
}
// 多分支
if (score >= 90) {
cout << "优秀" << endl;
} else if (score >= 80) {
cout << "良好" << endl;
} else if (score >= 70) {
cout << "中等" << endl;
} else if (score >= 60) {
cout << "及格" << endl;
} else {
cout << "不及格" << endl;
}
return 0;
}
switch语句
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "星期一" << endl;
break;
case 2:
cout << "星期二" << endl;
break;
case 3:
cout << "星期三" << endl;
break;
case 4:
cout << "星期四" << endl;
break;
case 5:
cout << "星期五" << endl;
break;
case 6:
case 7:
cout << "周末" << endl;
break;
default:
cout << "无效的日期" << endl;
}
return 0;
}
while循环
#include <iostream>
using namespace std;
int main() {
// 计算1到100的和
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
cout << "1到100的和:" << sum << endl;
return 0;
}
do-while循环
#include <iostream>
using namespace std;
int main() {
int num;
// 至少执行一次
do {
cout << "请输入一个正数(输入0退出):";
cin >> num;
if (num > 0) {
cout << "你输入的是:" << num << endl;
}
} while (num != 0);
cout << "程序结束" << endl;
return 0;
}
for循环
#include <iostream>
using namespace std;
int main() {
// 打印1到10
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
cout << endl;
// 打印九九乘法表
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
cout << j << "x" << i << "=" << (i*j) << "\t";
}
cout << endl;
}
return 0;
}
break和continue
#include <iostream>
using namespace std;
int main() {
// break:跳出循环
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // 遇到5就退出循环
}
cout << i << " ";
}
cout << endl; // 输出:1 2 3 4
// continue:跳过本次循环
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // 跳过5
}
cout << i << " ";
}
cout << endl; // 输出:1 2 3 4 6 7 8 9 10
return 0;
}
嵌套循环
#include <iostream>
using namespace std;
int main() {
// 打印矩形
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; j++) {
cout << "* ";
}
cout << endl;
}
// 打印三角形
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
goto语句(不推荐使用)
#include <iostream>
using namespace std;
int main() {
int num = 0;
start:
num++;
cout << num << " ";
if (num < 5) {
goto start; // 跳转到start标签
}
cout << endl;
return 0;
}
练习题
- 编写程序判断一个数是正数、负数还是零
- 使用循环计算1到100之间所有偶数的和
- 编写程序打印菱形图案
- 使用循环判断一个数是否为质数
- 编写猜数字游戏(1-100之间)