要執行程式或代碼的一部分幾次或多次,我們可以使用C語言的do-while
迴圈。 在do
和while
之間給出的代碼將被執行,直到條件(condition
)成為true
。
在do-while
迴圈中,語句在條件之前給出,所以語句或代碼將至少有一次執行。換句話說,我們可以說do-while
迴圈執行語句一次或多次。
如果你希望至少執行一次代碼,使用do-while
迴圈是最好不過的選擇。
do-while迴圈語法
C語言do-while
迴圈的語法如下:
do{
//code to be executed
}while(condition);
do-while迴圈的流程圖
do-while迴圈的例子
下麵給出了C語言的簡單程式,while
迴圈來列印連續的數據。創建一個原始檔案:do-while-example.c,其代碼如下所示 -
#include <stdio.h>
#include <conio.h>
void main() {
int i = 1, number = 0;
printf("Enter a number: ");
scanf("%d", &number);
do {
printf("%d \n", (i));
i++;
} while (i <= number);
}
執行上面代碼,得到以下結果 -
Enter a number: 12
1
2
3
4
5
6
7
8
9
10
11
12
請按任意鍵繼續. . .
使用do while迴圈列印給定數字表的程式
實現一個輸入數的倍數列印,創建一個原始檔案:do-while-print-table.c,參考以下代碼的實現 -
#include <stdio.h>
#include <conio.h>
void main() {
int i = 1, number = 0;
printf("Enter a number: ");
scanf("%d", &number);
do {
printf("%d \n", (number*i));
i++;
} while (i <= 10);
}
執行上面示例代碼,得到以下結果 -
Enter a number: 8
8
16
24
32
40
48
56
64
72
80
無限do-while迴圈
如果在do while
迴圈中使用條件運算式的值1,則它將運行無限次數。
do{
// 要執行的語句
}while(1);
上一篇:
C語言迴圈
下一篇:
C語言while迴圈