循環語句是編程中用于重復執行一段代碼直到滿足特定條件的控制結構。在 C# 中,循環語句包括 for
、while
、do-while
和 foreach
。本課程將逐一介紹這些循環語句的特點和使用場景,并通過示例加深理解。
1. for 循環
應用特點
應用場景
示例
// 簡單的計數循環
for (int i = 0; i < 10; i++) {
Console.WriteLine("計數值:" + i);
}
// 遍歷數組
int[] array = { 1, 2, 3, 4, 5 };
for (int i = 0; i < array.Length; i++) {
Console.WriteLine("數組元素:" + array[i]);
}
2. while 循環
應用特點
while
循環在每次迭代開始前檢查條件。
適用于循環次數未知的情況。
應用場景
等待用戶輸入或外部事件觸發。
持續檢查某個條件是否滿足。
示例
// 條件控制循環
int i = 0;
while (i < 10) {
Console.WriteLine("計數值:" + i);
i++;
}
// 用戶輸入控制循環
string userInput;
do {
Console.WriteLine("請輸入 'exit' 退出循環:");
userInput = Console.ReadLine();
} while (userInput != "exit");
3. do-while 循環
應用特點
應用場景
示例
// 至少執行一次的循環
int count = 0;
do {
count++;
Console.WriteLine("執行次數:" + count);
} while (count < 5);
4. foreach 循環
應用特點
foreach
循環用于簡化集合或數組的遍歷。
直接操作集合中的每個元素,無需使用索引。
應用場景
讀取集合中的所有元素。
不需要修改集合中元素的情況。
示例
// 遍歷集合
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
foreach (string name in names) {
Console.WriteLine("姓名:" + name);
}
// 遍歷字典
Dictionary<string, string> capitals = new Dictionary<string, string> {
{ "France", "Paris" },
{ "Germany", "Berlin" }
};
foreach (KeyValuePair<string, string> item in capitals) {
Console.WriteLine("國家:" + item.Key + ", 首都:" + item.Value);
}
結語
C# 中的循環語句是編寫高效、可讀性強的代碼的基礎。選擇合適的循環結構可以簡化代碼邏輯,提高程序性能。通過本課程的學習,您應該能夠靈活運用不同的循環語句來處理各種重復執行的任務。
該文章在 2024/12/12 10:22:48 編輯過