一、介紹
C++ 中的 for 循環用於重複執行一段代碼,主要有三種形式:
- 傳統 for 循環(C 風格)
for (初始化; 條件; 迭代) {
// 循環體
}
- 初始化:循環開始前執行一次(如 int i = 0)。
- 條件:每次循環前檢查,為 true 則繼續,false 則退出。
- 迭代:每次循環結束後執行(如 i++)。
- 範圍 for 循環(C++11 起)
用於遍歷容器(數組、vector、string 等)中的每個元素:
for (元素類型 變量 : 容器) {
// 循環體
}
- 基於聲明的 for 循環(C++17 起,較少用)
可在循環初始化中定義變量(作用域僅限循環內):
for (int i = 0, n = vec.size(); i < n; ++i) { ... }
// 或
for (auto it = map.begin(); it != map.end(); ++it) { ... }
二、示例
#include<iostream>
#include <array>
using namespace std;
int main(){
for (int i = 0; i < 5; i++) {
cout << "C++ konws loops." << endl;
}
cout << "C++ konws when to stop." << endl;
/*
C++ konws loops.
C++ konws loops.
C++ konws loops.
C++ konws loops.
C++ konws loops.
C++ konws when to stop.
*/
return 0;
}
示例1:
/*
for循環的練習1
用户輸出一個單詞,我們對其進行反轉,比如用户輸入xaye我們輸出eyax
*/
#include<iostream>
#include <array>
using namespace std;
int main(){
// 1.提示用户輸入單詞
string word;
cout << "請輸入一個單詞:";
cin >> word;
// 2. 反向輸出 xaye -> eyax
// for (int i = word.size() - 1; i > -1; i--) {
// cout << word[i];
// }
// cout << endl;
// 或 進行交換之後再輸出
int i, j;
for (i = 0, j = word.size() - 1; i < j; ++i, --j) {
// 交換
char ci = word[i];
word[i] = word[j];
word[j] = ci;
}
cout << word << endl;;
return 0;
}
xaye@orange:~/code/dev/15$ ./a.out
請輸入一個單詞:xaye
eyax
示例2:
/*
for循環的練習2
輸出n的階乘,比如n=10那麼輸出
0! = 1
1! = 1
2! = 2
3 != 6
...
n! = n * (n - 1)!
*/
#include<iostream>
using namespace std;
int main() {
// 1. 定義數組把階乘存起來
int n = 10;
long long factorials[n];
// 2. for 循環計算階乘存到數組裏
factorials[0] = factorials[1] = 1LL;
for (int i = 2; i <= n; i++) {
// n! = n * (n - 1)!
factorials[i] = i * factorials[i - 1];
}
// 3. for 循環輸出階乘
for (int i = 0; i <= n; i++) {
cout << i << "! = " << factorials[i] << endl;
}
return 0;
}
xaye@orange:~/code/dev/15$ ./a.out
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
示例3:
/*
用户輸出可以指定輸出多個數,然後依次輸入各個數,最後計算平均值輸出。
我來幫你計算平均值
請輸入數的個數:
請輸入第i個數:
這些數的平均值為:
*/
#include<iostream>
using namespace std;
int main() {
// 我們寫代碼為了達到需求,代碼是可以隨意寫,但是肯定會有更好的方案
// 1. 提示和接收用户的輸入,for循環
int number;
cout << "我來幫你計算平均值" << endl;
cout << "請輸入數的個數:" << endl;
cin >> number; // 10 -> int[10]
// 2. 怎麼計算輸出平均值,求和,和怎麼來,可以把數據存到數組,也可以用臨時變量記錄
int sum = 0;
for (int i = 0; i < number; i++) {
cout << "請輸入第" << (i + 1) << "個數:" << endl;
int user_input;
cin >> user_input;
sum += user_input; // sum = sum + user_input;
}
float avg = sum * 1.0f / number;
cout << "這些數的平均值為:" << avg << endl;
return 0;
}
xaye@orange:~/code/dev/15$ ./a.out
我來幫你計算平均值
請輸入數的個數:
4
請輸入第1個數:
1
請輸入第2個數:
2
請輸入第3個數:
3
請輸入第4個數:
4
這些數的平均值為:2.5