系列: C++
cpp
355 行
· 更新于 2026-04-03
loops.cpp
C++/Part1_基礎入門/Ch03_控制流程/loops.cpp
// ============================================================
// Ch03 - 迴圈示範(for, while, do-while, range-based for)
// 編譯:g++ -std=c++17 -Wall -o loops loops.cpp
// 執行:./loops
// ============================================================
#include <iostream>
#include <vector>
#include <string>
int main() {
// ══════════════════════════════════════════
// 1. for 迴圈 — 基本用法
// ══════════════════════════════════════════
std::cout << "=== for 迴圈 ===" << std::endl;
// 基本:從 1 數到 10
std::cout << "1 到 10:";
for (int i = 1; i <= 10; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
// 倒數
std::cout << "倒數:";
for (int i = 10; i >= 1; i--) {
std::cout << i << " ";
}
std::cout << std::endl;
// 每次增加 2(輸出偶數)
std::cout << "偶數:";
for (int i = 2; i <= 20; i += 2) {
std::cout << i << " ";
}
std::cout << std::endl;
// 每次乘以 2(輸出 2 的次方)
std::cout << "2 的次方:";
for (int i = 1; i <= 1024; i *= 2) {
std::cout << i << " ";
}
std::cout << std::endl;
// 累加 1 到 100
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
std::cout << "1 + 2 + ... + 100 = " << sum << std::endl;
// ══════════════════════════════════════════
// 2. while 迴圈
// ══════════════════════════════════════════
std::cout << "\n=== while 迴圈 ===" << std::endl;
// 基本:從 1 數到 5
std::cout << "while 計數:";
int count = 1;
while (count <= 5) {
std::cout << count << " ";
count++;
}
std::cout << std::endl;
// 計算位數
int number = 123456;
int digits = 0;
int temp = number;
while (temp > 0) {
digits++;
temp /= 10;
}
std::cout << number << " 有 " << digits << " 位數" << std::endl;
// 找出最大的 2 的次方(不超過 1000)
int power = 1;
while (power * 2 <= 1000) {
power *= 2;
}
std::cout << "不超過 1000 的最大 2 的次方:" << power << std::endl;
// ══════════════════════════════════════════
// 3. do-while 迴圈(至少執行一次)
// ══════════════════════════════════════════
std::cout << "\n=== do-while 迴圈 ===" << std::endl;
// 即使條件一開始為 false,也會執行一次
int val = 100;
std::cout << "do-while(條件為 false):";
do {
std::cout << val << " ";
val++;
} while (val < 5); // 條件一開始就是 false,但仍執行了一次
std::cout << "(只執行了一次)" << std::endl;
// 對比 while(條件為 false 則一次都不執行)
val = 100;
std::cout << "while(條件為 false):";
while (val < 5) {
std::cout << val << " ";
val++;
}
std::cout << "(完全沒執行)" << std::endl;
// 模擬使用者輸入驗證
std::cout << "\n模擬輸入驗證(模擬輸入 -1, 0, 5):" << std::endl;
int inputs[] = {-1, 0, 5};
int idx = 0;
int input;
do {
input = inputs[idx++];
std::cout << " 輸入:" << input;
if (input <= 0) {
std::cout << " → 無效,請輸入正數" << std::endl;
}
} while (input <= 0 && idx < 3);
if (input > 0) {
std::cout << " → 有效!" << std::endl;
}
// ══════════════════════════════════════════
// 4. 範圍 for 迴圈(Range-based for,C++11)
// ══════════════════════════════════════════
std::cout << "\n=== 範圍 for 迴圈 ===" << std::endl;
// 遍歷 C 風格陣列
int arr[] = {10, 20, 30, 40, 50};
std::cout << "陣列元素:";
for (int value : arr) {
std::cout << value << " ";
}
std::cout << std::endl;
// 遍歷 std::vector
std::vector<std::string> fruits = {"蘋果", "香蕉", "橘子", "芒果", "葡萄"};
std::cout << "水果:";
for (const std::string& fruit : fruits) {
std::cout << fruit << " ";
}
std::cout << std::endl;
// 使用 auto 簡化(推薦寫法)
std::cout << "auto 版:";
for (const auto& fruit : fruits) {
std::cout << fruit << " ";
}
std::cout << std::endl;
// 使用參考修改元素
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::cout << "原始:";
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
// 加上 & 才能修改原始元素
for (int& n : numbers) {
n *= 2;
}
std::cout << "加倍:";
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
// ══════════════════════════════════════════
// 5. break — 提前跳出迴圈
// ══════════════════════════════════════════
std::cout << "\n=== break ===" << std::endl;
// 找到第一個能被 7 整除的數
std::cout << "第一個能被 7 整除的數(從 50 開始):";
for (int i = 50; i <= 100; i++) {
if (i % 7 == 0) {
std::cout << i << std::endl;
break; // 找到就停止
}
}
// 線性搜尋
std::vector<int> data = {23, 45, 67, 89, 12, 34, 56};
int target = 89;
bool found = false;
int position = -1;
for (int i = 0; i < static_cast<int>(data.size()); i++) {
if (data[i] == target) {
found = true;
position = i;
break;
}
}
if (found) {
std::cout << "找到 " << target << " 在索引 " << position << std::endl;
} else {
std::cout << target << " 不在陣列中" << std::endl;
}
// ══════════════════════════════════════════
// 6. continue — 跳過本次迭代
// ══════════════════════════════════════════
std::cout << "\n=== continue ===" << std::endl;
// 跳過 3 的倍數
std::cout << "1-15(跳過 3 的倍數):";
for (int i = 1; i <= 15; i++) {
if (i % 3 == 0) {
continue; // 跳過本次,直接進入下一次迭代
}
std::cout << i << " ";
}
std::cout << std::endl;
// 只處理正數
std::vector<int> mixed = {3, -1, 4, -5, 2, -3, 8};
std::cout << "只輸出正數:";
for (int n : mixed) {
if (n <= 0) continue;
std::cout << n << " ";
}
std::cout << std::endl;
// ══════════════════════════════════════════
// 7. 巢狀迴圈 — 九九乘法表
// ══════════════════════════════════════════
std::cout << "\n=== 九九乘法表 ===" << std::endl;
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
// 格式化輸出,讓結果對齊
int result = i * j;
if (result < 10) {
std::cout << " ";
}
std::cout << i << "×" << j << "=" << result << " ";
}
std::cout << std::endl;
}
// ══════════════════════════════════════════
// 8. 巢狀迴圈 — 星號圖形
// ══════════════════════════════════════════
std::cout << "\n=== 星號圖形 ===" << std::endl;
// 直角三角形
std::cout << "直角三角形:" << std::endl;
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
std::cout << "* ";
}
std::cout << std::endl;
}
// 倒直角三角形
std::cout << "\n倒直角三角形:" << std::endl;
for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
std::cout << "* ";
}
std::cout << std::endl;
}
// 等腰三角形(金字塔)
std::cout << "\n金字塔:" << std::endl;
for (int i = 1; i <= rows; i++) {
// 先印空格
for (int j = 1; j <= rows - i; j++) {
std::cout << " ";
}
// 再印星號
for (int j = 1; j <= 2 * i - 1; j++) {
std::cout << "*";
}
std::cout << std::endl;
}
// ══════════════════════════════════════════
// 9. 無窮迴圈搭配 break
// ══════════════════════════════════════════
std::cout << "\n=== 無窮迴圈 + break ===" << std::endl;
// 模擬一個需要特定條件才停止的迴圈
int attempts = 0;
int secretNumber = 7;
int guesses[] = {3, 9, 5, 7, 2};
while (true) { // 無窮迴圈
int guess = guesses[attempts];
attempts++;
std::cout << "第 " << attempts << " 次猜測:" << guess;
if (guess == secretNumber) {
std::cout << " → 猜對了!" << std::endl;
break; // 猜對就跳出
} else if (guess < secretNumber) {
std::cout << " → 太小了" << std::endl;
} else {
std::cout << " → 太大了" << std::endl;
}
if (attempts >= 5) {
std::cout << "猜測次數用完了!" << std::endl;
break;
}
}
std::cout << "共猜了 " << attempts << " 次" << std::endl;
// 也可以用 for(;;) 寫無窮迴圈
// for (;;) { ... break; }
// ══════════════════════════════════════════
// 10. 實用範例:費波那契數列
// ══════════════════════════════════════════
std::cout << "\n=== 費波那契數列(前 15 項)===" << std::endl;
int fib1 = 0, fib2 = 1;
std::cout << fib1 << " " << fib2 << " ";
for (int i = 2; i < 15; i++) {
int next = fib1 + fib2;
std::cout << next << " ";
fib1 = fib2;
fib2 = next;
}
std::cout << std::endl;
// ══════════════════════════════════════════
// 11. for 迴圈的變化形式
// ══════════════════════════════════════════
std::cout << "\n=== for 迴圈變化 ===" << std::endl;
// 多個初始化與更新
std::cout << "雙變數:";
for (int i = 0, j = 10; i < j; i++, j--) {
std::cout << "(" << i << "," << j << ") ";
}
std::cout << std::endl;
// 省略部分(三個部分都可以省略)
// for (;;) { ... } 是無窮迴圈的另一種寫法
std::cout << "省略初始化:";
int k = 0;
for (; k < 5; k++) {
std::cout << k << " ";
}
std::cout << std::endl;
return 0;
}
相关文章
C++
c
更新于 2026-07-21
deviceAlpha.h
deviceAlpha.h — c source code from the C++ learning materials (C++/Mavis_Homework/FinalProject/deviceAlpha.h).
阅读文章 →
C++
c
更新于 2026-07-21
finalproject.c
finalproject.c — c source code from the C++ learning materials (C++/Mavis_Homework/FinalProject/finalproject.c).
阅读文章 →
C++
cpp
更新于 2026-07-21
finalproject.cpp
finalproject.cpp — cpp source code from the C++ learning materials (C++/Mavis_Homework/FinalProject/finalproject.cpp).
阅读文章 →
C++
c
更新于 2026-07-21
deviceAlpha.h
deviceAlpha.h — c source code from the C++ learning materials (C++/Mavis_Homework/Lab8/deviceAlpha.h).
阅读文章 →
C++
c
更新于 2026-07-21
lab8.c
lab8.c — c source code from the C++ learning materials (C++/Mavis_Homework/Lab8/lab8.c).
阅读文章 →
C++
cpp
更新于 2026-07-21
lab8.cpp
lab8.cpp — cpp source code from the C++ learning materials (C++/Mavis_Homework/Lab8/lab8.cpp).
阅读文章 →