D語言巢狀迴圈


D程式設計語言允許使用一個迴圈裡巢狀另一個迴圈。以下部分顯示幾個例子來說明這一概念。

語法

語法巢狀在D環語句如下:

for ( init; condition; increment )
{
   for ( init; condition; increment )
   {
      statement(s);
   }
   statement(s);
}

在D程式設計語言while迴圈語句語法巢狀如下:

while(condition)
{
   while(condition)
   {
      statement(s);
   }
   statement(s);
}

巢狀do...while的語法在D程式設計語言回圈語句如下:

do
{
   statement(s);
   do
   {
      statement(s);
   }while( condition );

}while( condition );

在迴圈巢狀最後需要說明的是,可以把任何型別的迴圈的任何其他型別的迴圈裡面。例如,一個for迴圈可以放在一個while迴圈中,反之亦然。

例子:

下面的程式使用一個巢狀的for迴圈來找出2-100的素數:

import std.stdio;
 
int main ()
{
   /* local variable definition */
   int i, j;
   
   for(i=2; i<100; i++) {
      for(j=2; j <= (i/j); j++)
        if(!(i%j)) break; // if factor found, not prime
      if(j > (i/j)) writefln("%d is prime", i);
   }
 
   return 0;
}

當上面的程式碼被編譯並執行,它會產生以下結果:

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