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