如何用 C# 建立巢狀 while 迴圈?


對於巢狀 while 迴圈,我們有兩個 while 迴圈。

第一個迴圈檢查條件,如果條件為真,則轉到內層迴圈,即巢狀迴圈。

迴圈 1

while (a<25) {
}

迴圈 2(在 loop1 內)

while (b<45){
}

要建立巢狀 while 迴圈,以下為示例程式碼。

示例

 動態演示

using System;
namespace Program {
   class Demo {
      public static void Main(string[] args) {
         int a=20;
         while (a<25) {
            int b=40;
            while (b<45) {
               Console.Write("({0},{1}) ", a, b);
               b++;
            }
            a++;
            Console.WriteLine();
         }
      }
   }
}

輸出

(20,40) (20,41) (20,42) (20,43) (20,44)
(21,40) (21,41) (21,42) (21,43) (21,44)
(22,40) (22,41) (22,42) (22,43) (22,44)
(23,40) (23,41) (23,42) (23,43) (23,44)
(24,40) (24,41) (24,42) (24,43) (24,44)

更新於: 2020 年 6 月 23 日

290 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告