第六课 循环结构

程序控制除了顺序结构、分支结构,还有循环结构,这是让程序焕发神奇最重要的部分。C++中的循环语句有for循环、while循环、do-while循环。

一、循环结构特点

  • 程序重复执行某段代码,直到满足特定条件才停止
  • 大大减少了重复代码的编写量
  • 让计算机发挥其擅长重复运算的优势

二、for循环(适合已知循环次数)

for (初始化; 条件; 更新) {
    // 循环体
}

for循环示例 – 输出0到9:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; i++) {
        cout << i << " ";
    }
    // 输出:0 1 2 3 4 5 6 7 8 9
    return 0;
}

for循环示例 – 计算1+2+…+10:

#include <iostream>
using namespace std;

int main() {
    int sum = 0;

    for (int i = 1; i <= 10; i++) {
        sum += i;  // 每次把i加到sum上
    }

    cout << "1+2+...+10 = " << sum << endl;  // 输出55
    return 0;
}

for循环示例 – 打印九九乘法表:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << "*" << i << "=" << i*j << "\t";
        }
        cout << endl;
    }
    return 0;
}

三、while循环(适合条件驱动)

while (条件) {
    // 循环体
}

while循环示例 – 计算1+2+…+10:

#include <iostream>
using namespace std;

int main() {
    int sum = 0;
    int i = 1;

    while (i <= 10) {
        sum += i;
        i++;  // 别忘了更新i,否则会死循环
    }

    cout << "1+2+...+10 = " << sum << endl;  // 输出55
    return 0;
}

while循环示例 – 计算阶乘:

#include <iostream>
using namespace std;

int main() {
    int n = 5;
    int result = 1;

    while (n > 0) {
        result *= n;  // result = result * n
        n--;
    }

    cout << "5! = " << result << endl;  // 输出120
    return 0;
}

四、do-while循环(至少执行一次)

do {
    // 循环体
} while (条件);

do-while示例:

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    do {
        cout << i << " ";
        i++;
    } while (i <= 10);
    // 输出:1 2 3 4 5 6 7 8 9 10
    return 0;
}

五、do-while vs while 区别

#include <iostream>
using namespace std;

int main() {
    // while:条件不满足可能一次都不执行
    int a = 10;
    while (a > 20) {
        cout << "while: 执行了" << endl;
    }
    // 不输出,因为条件一开始就不满足

    // do-while:至少执行一次
    int b = 10;
    do {
        cout << "do-while: 执行了" << endl;
    } while (b > 20);
    // 会输出一次

    return 0;
}

六、break和continue

  • break:跳出整个循环
  • continue:跳过本次循环,继续下次

break示例:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break;  // 当i等于5时跳出循环
        }
        cout << i << " ";
    }
    // 输出:1 2 3 4
    return 0;
}

continue示例:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // 偶数时跳过本次循环
        }
        cout << i << " ";
    }
    // 输出:1 3 5 7 9(只输出奇数)
    return 0;
}

七、死循环(永远不停止的循环)

// for死循环
for (;;) {
    // 永远执行
}

// while死循环
while (true) {
    // 永远执行
}

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注