VB.Net - Nested嵌套循環(huán)

2022-06-02 15:13 更新

VB.Net允許在另一個(gè)循環(huán)內(nèi)使用一個(gè)循環(huán)。 以下部分顯示了幾個(gè)例子來(lái)說(shuō)明這個(gè)概念。

語(yǔ)法:

VB.Net中嵌套For循環(huán)語(yǔ)句的語(yǔ)法如下:
For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ]
    For counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ]
    ...
    Next [ counter2 ]
Next [ counter 1]

VB.Net中嵌套While循環(huán)語(yǔ)句的語(yǔ)法如下:

While condition1
    While condition2
    ...
    End While
End While

VB.Net中嵌套Do ... While循環(huán)語(yǔ)句的語(yǔ)法如下:

Do { While | Until } condition1
    Do { While | Until } condition2
    ...
    Loop
Loop

關(guān)于循環(huán)嵌套的最后一點(diǎn)是,你可以把任何類(lèi)型的循環(huán)放在任何其他類(lèi)型的循環(huán)里面。 例如,for循環(huán)可以在while循環(huán)內(nèi),反之亦然。

示例:

以下程序使用嵌套for循環(huán)來(lái)查找從2到100的素?cái)?shù):
Module loops
   Sub Main()
      ' local variable definition 
      Dim i, j As Integer
      For i = 2 To 100
          For j = 2 To i
              ' if factor found, not prime
              If ((i Mod j) = 0) Then
                  Exit For
              End If
          Next j
          If (j > (i \ j)) Then
              Console.WriteLine("{0} is prime", i)
          End If
      Next i
      Console.ReadLine()
   End Sub
End Module
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生以下結(jié)果:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)