C# 中支援哪些型別的迴圈?
迴圈語句允許我們多次執行語句或一組語句。C# 中支援以下迴圈 −
| 序號 | 迴圈型別和說明 |
|---|---|
| 1 | while 迴圈 在給定條件為 true 時重複一條語句或一組語句。它在執行迴圈體之前測試條件。 |
| 2 | for 迴圈 多次執行一系列語句並縮寫管理迴圈變數的程式碼。 |
| 3 | do...while 迴圈 類似於 while 語句,但它在迴圈體末尾測試條件 |
藉助 C#,還可以使用 foreach 迴圈,如下所示 −
示例
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int [] n = new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for ( int i = 0; i < 10; i++ ) {
n[i] = i + 100;
}
/* output each array element's value */
foreach (int j in n ) {
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}輸出
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP