C# 支援哪些型別的迴圈?
迴圈語句允許我們多次執行語句或一組語句。C# 中支援的迴圈如下 −
| 序號 | 迴圈型別和說明 |
|---|---|
| 1 | while 迴圈 只要給定的條件為真,它就會重複執行語句或一組語句。它在執行迴圈體之前測試條件。 |
| 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP