vb.net 教程 2-4 流程控制:循环语句 For each...Next

来源:互联网 发布:cctv下载网络电视下载安装 编辑:程序博客网 时间:2024/06/04 22:46

当需要为集合或数组的每个元素重复执行一组语句时,可以使用 For Each...Next 循环,通过For Each遍历出每个元素。


还是采用《流程控制:循环语句 For...Next》中的题目
一组数按照由小到大的顺序进行排序:
    Sub Main()        '需要排序的数字在数组内        Dim source() As Integer = {32, 12, 44, 43, 79, 1, 10, 65, 21, 53}        '外层循环每一次循环结束时,输出数组        Dim outputString As String = ""        '对循环次数进行计数        Dim counti As Integer = 0        Dim i As Integer        Dim j As Integer        Dim tmp As Integer        '循环        For i = 0 To 8            outputString = ""            '嵌套循环            For j = 0 To (8 - i)                '循环次数+1                counti += 1                '如果前面那个数大于后面那个数,就把前面那个数排到后面                If source(j) > source(j + 1) Then                    tmp = source(j)                    source(j) = source(j + 1)                    source(j + 1) = tmp                End If            Next            '枚举出source中的每个元素            For Each k As Integer In source                outputString &= k & " "            Next            Console.WriteLine(outputString)        Next        '输出循环次数        Console.WriteLine("循环次数:{0}", counti)        Console.ReadKey()    End Sub
运行结果如下:
可以看到外层循环了9次,虽然在第5次就得到了正确的结果,但是这个只是和代码内数组中的数值顺序有关系。
各位读者可以更换一下顺序:Dim source() As Integer = {79, 65, 53, 44, 12, 10, 21, 32, 43, 1}
0 0