c++之循环
目录
C++循环结构完全解析:从基础到实战应用
一、for循环结构
二、while循环结构
三、do-while循环结构
四、范围for循环(C++11)
五、循环控制语句
C++循环结构完全解析:从基础到实战应用
循环结构是编程语言的核心控制结构之一,本文将深入讲解C++中的四种循环方式,并提供多个实用代码示例。
一、for循环结构
for循环是最常用的确定性循环结构,其基本格式为: $$ \text{for}(初始化表达式; 条件表达式; 更新表达式) $$
示例1:基础计数循环
#include <iostream>
using namespace std;int main() {for(int i = 1; i <= 5; ++i) {cout << "当前数值:" << i << endl;}return 0;
}
输出结果:
当前数值:1
当前数值:2
当前数值:3
当前数值:4
当前数值:5
示例2:复合条件循环
#include <iostream>
using namespace std;int main() {for(int a=0, b=10; a < b; a+=2, b-=1) {cout << "a=" << a << ", b=" << b << endl;}return 0;
}
输出结果:
a=0, b=10
a=2, b=9
a=4, b=8
二、while循环结构
while循环适用于不确定循环次数的场景,先判断后执行。
示例1:输入验证
#include <iostream>
using namespace std;int main() {int password;cout << "请输入密码(123456):";cin >> password;while(password != 123456) {cout << "密码错误,请重新输入:";cin >> password;}cout << "登录成功!" << endl;return 0;
}
示例2:数据过滤
#include <iostream>
using namespace std;int main() {int num = 1024;while(num > 2) {num /= 2;cout << num << " ";}return 0;
}
输出结果:
512 256 128 64 32 16 8 4 2
三、do-while循环结构
至少执行一次循环体,适合需要先执行后判断的场景。
示例1:菜单系统
#include <iostream>
using namespace std;int main() {char choice;do {cout << "\n1. 开始游戏\n2. 设置\n3. 退出\n请选择:";cin >> choice;switch(choice) {case '1': cout << "游戏开始!"; break;case '2': cout << "进入设置"; break;case '3': cout << "再见!"; break;default: cout << "无效选项";}} while(choice != '3');return 0;
}
示例2:数学计算
#include <iostream>
using namespace std;int main() {int n, sum = 0;cout << "输入正整数:";cin >> n;do {sum += n%10;n /= 10;} while(n > 0);cout << "各位数字之和:" << sum;return 0;
}
四、范围for循环(C++11)
专为遍历容器设计的简化循环结构。
示例1:数组遍历
#include <iostream>
using namespace std;int main() {int nums[] = {2, 4, 6, 8, 10};for(int num : nums) {cout << num * 2 << " ";}return 0;
}
输出结果:
4 8 12 16 20
示例2:字符串处理
#include <iostream>
#include <string>
using namespace std;int main() {string msg = "Hello";for(char &c : msg) {c = toupper(c);}cout << msg; // 输出:HELLOreturn 0;
}
五、循环控制语句
break
:立即终止当前循环continue
:跳过本次循环剩余代码- 循环嵌套:最多支持256层嵌套(视编译器而定)
实践建议:
- 优先选择for循环处理确定次数的场景
- 使用while循环处理不确定次数的迭代
- 需要至少执行一次时使用do-while
- 范围for循环最适合容器遍历
掌握这些循环结构的特性,能够显著提升代码效率和可读性。建议通过实际项目练习不同循环结构的组合应用,加深对循环控制的理解。