章节概述

循环结构用于重复执行一段代码,是处理批量数据、迭代计算的核心机制。
包括 for、while、do-while 三种形式。

核心原理

1. 三种循环对比

循环特点适用场景
for初始化→条件→迭代 一体已知次数
while先判断后执行条件驱动
do-while先执行后判断至少执行一次

2. 循环控制

关键字作用
break跳出最内层循环
continue跳过本次剩余,进入下次迭代

3. 常见循环模式

// 数字逐位处理
while (n) { int digit = n % 10; n /= 10; }
 
// 等比递减
double step = 2.0;
while (condition) { step *= 0.98; }
 
// 双重循环 (i < j 避免重复)
for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++) ...

关键数据结构


P1423 小玉在游泳

题目: 第一步游 2 米,每一步距离是上一步的 98%。问需要多少步才能游超过 s 米。

#include <iostream>
using namespace std;
int main() {
    double s;
    cin >> s;
    double step = 2.0, total = 0;
    int cnt = 0;
    while (total < s) {
        total += step;
        step *= 0.98;
        cnt++;
    }
    cout << cnt << endl;
    return 0;
}

P1035 [NOIP2002 普及组] 级数求和

题目: 求最小的 n 使得 S_n = 1+1/2+1/3+…+1/n > k。

#include <iostream>
using namespace std;
int main() {
    int k, n = 0;
    double s = 0;
    cin >> k;
    while (s <= k) {
        n++;
        s += 1.0 / n;
    }
    cout << n << endl;
    return 0;
}

P1307 [NOIP2011 普及组] 数字反转

题目: 反转整数的各位数字。

#include <iostream>
using namespace std;
int main() {
    int n, rev = 0;
    cin >> n;
    int sign = (n < 0) ? -1 : 1;
    n = abs(n);
    while (n) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    cout << rev * sign << endl;
    return 0;
}

P1980 [NOIP2013 普及组] 计数问题

题目: 试计算 1 到 n 的所有整数中,数字 x 出现了多少次。

#include <iostream>
using namespace std;
int main() {
    int n, x, cnt = 0;
    cin >> n >> x;
    for (int i = 1; i <= n; i++) {
        int t = i;
        while (t) {
            if (t % 10 == x) cnt++;
            t /= 10;
        }
    }
    cout << cnt << endl;
    return 0;
}

推荐练习题(洛谷)


相关技巧


多平台练习

| 洛谷 | 本题单 | 竞赛基础 |
| POJ (北大) | PKU JudgeOnline | 经典题目,适合巩固 |
| HDU (杭电) | HDU OJ | 暑期多校训练 |
| Codeforces | Codeforces | 国际竞赛,适合提升 |