帕斯卡 - 重複-直到迴圈



與在迴圈開頭測試迴圈條件的for和while迴圈不同,帕斯卡中的repeat ... until迴圈在迴圈的底部檢查其條件。

repeat ... until迴圈類似於while迴圈,但repeat ... until迴圈保證至少執行一次。

語法

repeat
   S1;
   S2;
   ...
   ...
   Sn;
until condition;

例如:

repeat
   sum := sum + number;
   number := number - 2;
until number = 0;

請注意,條件表示式出現在迴圈的末尾,因此迴圈中的語句在條件被測試之前執行一次。

如果條件為假,控制流會跳回到repeat,並且迴圈中的語句會再次執行。此過程會重複,直到給定條件變為真。

流程圖

repeat until loop in Pascal

示例

program repeatUntilLoop;
var
   a: integer;

begin
   a := 10;
   (* repeat until loop execution *)
   repeat
      writeln('value of a: ', a);
      a := a + 1
   until a = 20;
end.

編譯並執行以上程式碼後,會產生以下結果 -

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
pascal_loops.htm
廣告
© . All rights reserved.