1. 为什么需要for循环?
前面的while循环适合“不知道次数,但知道条件”的情况。而for循环专门用来处理“知道确切循环次数”的场景,比如:
简单说:while强调“条件”,for强调“次数”。
2. for循环的基本用法
2.1 语法格式
for (初始化; 循环条件; 变量更新) { // 循环体部分}
执行初始化(只执行一次)
判断循环条件
执行变量更新
回到第2步继续判断
2.2 最简单的例子:输出1到10
#include<bits/stdc++.h>using namespace std;intmain(){ for(int i = 1; i <= 10; i++) { cout << i << " "; } // 输出:1 2 3 4 5 6 7 8 9 10 return 0;}
3. for循环的四大要素
与while相同,for循环也有四要素,但写法更紧凑: | | |
|---|
| int i = 1 | |
| i <= 10 | |
| i++ | |
| { cout << i; } | |
// while写法int i = 1;// 初始化while (i <= 10)// 条件{ cout << i << " "; i++;// 更新}// for写法(更简洁)for (int i = 1; i <= 10; i++)// 三合一{ cout << i << " ";}
4. for循环的常见应用
4.1 累加求和(1加到n)
#include<bits/stdc++.h>using namespace std;intmain(){ int n; cin >> n; int sum = 0; for (int i = 1; i <= n; i++) //实现从1~n的循环 { sum = sum + i;// 或 sum += i } cout << sum; return 0;}
4.2 累乘求阶乘(n!)
#include<bits/stdc++.h>using namespace std;intmain(){ int n; cin >> n; long long sum = 1;//答案比较大 用long long for (int i = 1; i <= n; i++) //实现从1~n的循环 { sum = sum * i;// 或 sum *= i } cout << sum; return 0;}
4.3 输出特定范围内的数
输出1到100中所有能被3整除的数:
#include<bits/stdc++.h>using namespace std;intmain(){ for(int i = 1; i <= 100; i++) //从1~100进行遍历 { if (i % 3 == 0)//满足条件 { cout << i << " "; } } return 0;}
#include<bits/stdc++.h>using namespace std;intmain(){ // 直接从3开始,每次加3 for(int i = 3; i <= 100; i += 3) { cout << i << " "; } return 0;}
4.4 反向循环(从大到小)
#include<bits/stdc++.h>using namespace std;intmain(){ // 输出10到1 for(int i = 10; i >= 1; i--) { cout << i << " "; } // 输出:10 9 8 7 6 5 4 3 2 1 return 0;}
5. 循环中的break和continue
5.1 break —— 跳出整个循环
#include<bits/stdc++.h>using namespace std;intmain(){ // 找到第一个能被7整除的数就停止 for(int i = 1; i <= 100; i++) { if(i % 7 == 0) { cout << i << " "; break; // 找到后立即退出循环 } } return 0;}
5.2 continue —— 跳过本次循环
#include<bits/stdc++.h>using namespace std;intmain(){ // 输出1-10中所有奇数(跳过偶数) for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue;// 偶数直接跳过,不输出 } cout << i << " "; } // 输出:1 3 5 7 9 return 0;}
注意: 与while不同,for循环中使用continue时,不需要担心变量更新问题,因为更新语句在for的括号里会自动执行,for中使用continue更加的安全。6.小结
for循环适合“知道循环次数”的场景,语法简洁:for(初始化;条件;更新)
执行顺序:初始化 → 判断条件 → 循环体 → 更新 → 再判断...
break:跳出整个循环
continue:跳过本次循环(for中用起来很安全)
可以灵活省略括号内的部分,但分号必须保留