do
<循環主體>;
while (<條件>);
如果循環主體多於一個語句,它必須被一對大括號包圍著。
在 do-while 循環中,程序是在循環主體被執行後才檢查條件的。如果條件的值不是零(即是「真」),控制會回到循環主體最開始的地方,然後再執行循環主體。如果條件的值是零(即是「假」),程序會離開這個循環。
C++ 的 do-while 結構和以下各種結構等同︰
在 C++ 中使用 while 語句時的等同結構 | <循環主體>; while (<條件>) <循環主體>; |
在 Pascal 中使用 repeat-until 語句時的等同結構 | repeat <循環主體> until not <條件> |
do-while 循環 | while 循環 |
循環主體會被執行至少一次。 | 循環主體有可能不被執行(當程序剛進入循環時條件已經等於零的時候)。 |
條件是在循環主體被執行之後才被檢查的。 | 條件是在循環主體被執行之前被檢查的。 |
C++ 中的 do-while 循環 | Pascal 中的 repeat-until 循環 |
當條件是錯(等於零)的時候,程序會離開該循環。 | 當條件是對(不等於零)的時候,程序會離開該循環。 |
這個程序和程序十八一樣,分別只是這個程序的循環當中只用了一個 cin 語句;這是因為這兒用了do-while 循環。
C++ 版本(使用 do-while 循環) | Pascal 版本(使用 repeat-until 循環) |
#include <iostream.h> main() { int score, sum = 0; do { cout << "Enter score (-1 to quit): "; cin >> score; if (score != -1) sum += score; } while (score != -1); cout << "Sum = " << sum << endl; return 0; } |
program prog_19(input, output); var score, sum: integer; begin sum := 0; repeat write('Enter score (-1 to quit): '); readln(score); if score <> -1 then sum := sum + score until score = -1; writeln('Sum = ', sum); end. |
for (<算式1>; <算式2>; <算式3>)
<循環主體>;
如果循環主體包含多於一個語句時,它應該被一對大括號包圍著。
以上 C++ 的 for 結構和以下的結構是等同的︰
<算式1>;
while (<算式2>) {
<循環主體>;
<算式3>;
}
因此程序十六可以改寫成以下樣子︰
#include <iostream.h> main() { int n, product; cout << "n? "; cin >> n; for (product = n; product <= 1000; product *= n) cout << product << endl; return 0; } |
通常 for 語句被用作計數器控制循環。在這情況下,<算式1> 是一個初始化語句,<算式2> 是一個用來測試是否已到終值的算式,而 <算式3> 表示計數器變量在循環中是如何被增值(或減值)的。
C++ 中的計數器控制循環(使用 for) | for (<計數器> = <初值>; <計數器>
<= <終值>; <計數器>++) <循環主體>; |
C++ 中等同的計數器控制循環(使用 while) | <計數器> =
<初值>; while (<計數器> <= <終值>) { <循環主體>; <計數器>++; } |
Pascal 中等同的控制結構 | for <計數器> := <初值> to <終值>
do <循環主體> |
以下展示程序十七(包含一個計數器控制循環)如何利用 for 語句去改寫︰
C++ 版本 | Pascal 版本 |
#include <iostream.h> main() { int score, sum, i; sum = 0; for (i = 1; i <=5; i++) { cout << "Score No. " << i << ": "; cin >> score; sum += score; } cout << "Sum = " << sum << endl; return 0; } |
program prog_21(input, output); var score, sum, i: integer; begin sum := 0; for i := 1 to 5 do begin write('Score No. ', i, ': '); readln(score); sum := sum + score; end; writeln('Sum = ', sum) end. |