如何使用“ foreach”循环在C#中遍历数组?
for循环类似于for循环;但是,对数组或组中的每个元素执行循环。因此,索引在foreach循环中不存在。
让我们看一个冒泡排序的例子,其中对元素排序之后,我们将使用foreach循环显示元素。
foreach (int p in arr) Console.Write(p + " ");
以下是完整的示例。
示例
using System;
namespace BubbleSort {
class MySort {
static void Main(string[] args) {
int[] arr = { 78, 55, 45, 98, 13 };
int temp;
for (int j = 0; j <= arr.Length - 2; j++) {
for (int i = 0; i <= arr.Length - 2; i++) {
if (arr[i] > arr[i + 1]) {
temp= arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
Console.WriteLine("Sorted:");
foreach (int p in arr)
Console.Write(p + " ");
Console.Read();
}
}
}输出结果
Sorted: 13 45 55 78 98
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短