跳轉到內容

程式設計基礎/巢狀迴圈

來自華夏公益教科書

巢狀 for 迴圈將一個 for 迴圈放在另一個 for 迴圈裡面。內部迴圈會針對外部迴圈的每次迭代重複執行。

巢狀控制結構

[編輯 | 編輯原始碼]

我們首先介紹巢狀控制結構的概念。巢狀是指將一個專案放置在另一個專案內部。例如

if expression
    true action
else 
    false action

這是 if then else 控制結構的基本形式。現在考慮

if age is less than 18
    you can't vote
    if age is less than 16
        you can't drive
    else
        you can drive
else
    you can vote
    if age is less than 21
        you can't drink 
    else
        you can drink

如您所見,我們在 “true action” 部分簡單地包含了一個語句和另一個 if then else 控制結構。我們對 “false action” 進行了同樣的操作(嵌套了另一個 if then else)。在我們的示例中,我們嵌套了 if then else 控制結構。巢狀可以包含一個在 while 迴圈內部的 if then else。因此,巢狀的概念允許混合不同型別的控制結構。

許多複雜的邏輯問題需要使用巢狀控制結構。透過巢狀控制結構(或將一個控制結構放在另一個內部),我們可以解決幾乎所有複雜的邏輯問題。

示例 - 巢狀 for 迴圈

[編輯 | 編輯原始碼]

以下是一個 10 x 10 乘法表的示例

         1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10 |
     -------------------------------------------------------------
   1 !   1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10 |
   2 !   2 |   4 |   6 |   8 |  10 |  12 |  14 |  16 |  18 |  20 |
   3 !   3 |   6 |   9 |  12 |  15 |  18 |  21 |  24 |  27 |  30 |
   4 !   4 |   8 |  12 |  16 |  20 |  24 |  28 |  32 |  36 |  40 |
   5 !   5 |  10 |  15 |  20 |  25 |  30 |  35 |  40 |  45 |  50 |
   6 !   6 |  12 |  18 |  24 |  30 |  36 |  42 |  48 |  54 |  60 |
   7 !   7 |  14 |  21 |  28 |  35 |  42 |  49 |  56 |  63 |  70 |
   8 !   8 |  16 |  24 |  32 |  40 |  48 |  56 |  64 |  72 |  80 |
   9 !   9 |  18 |  27 |  36 |  45 |  54 |  63 |  72 |  81 |  90 |
  10 !  10 |  20 |  30 |  40 |  50 |  60 |  70 |  80 |  90 | 100 |

我們可能還會發現,答案可以設計成一系列單元格(每個單元格正好六個空格寬)。生成部分表格的虛擬碼為

For row = 1, row <= 3, row += 1
    For column = 1, column <= 3, column += 1
        Output row * column
        Output "\t"
    Output "\n"

示例 - 巢狀 Do While For 迴圈

[編輯 | 編輯原始碼]

請輸入您要乘以的數字 3 您要乘以的常數 2 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 您要進行另一組運算嗎?輸入 yes 或 no 好的,再見

以下是上述示例的虛擬碼

Function Main
    Declare Integer answer
    Declare Integer multiply
    Declare Integer constant
    Declare String choice
    
    Loop
        Output "Please input what number you want to multiply"
        Input multiply
        Output "What number do you want constant"
        Input constant
        Declare Integer i
        
        Assign i = 0
        For i = 1 to multiply
            Assign answer = i * constant
            Output constant & " x " & i & " = " & answer
        End
        Output "Would you like another set? Type yes"
        Input choice
    Do choice == "Yes"
    Output "Ok bye"
End

關鍵詞

[編輯 | 編輯原始碼]
複雜邏輯
通常用巢狀控制結構解決。

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書