本文目錄一覽:
C語言do-while語句
do/while
循環是
while
循環的變體。在檢查條件是否為真之前,該循環首先會執行一次代碼塊,然後檢查條件是否為真,如果條件為真的話,就會重複這個循環。適合用於在循環次數未知的情況下判斷是否達到條件並打印最後一位數。
do-while
和
while循環非常相似,區別在於表達式的值是在每次循環結束時檢查而不是開始時。和正規的
while
循環主要的區別是
do-while
的循環語句保證會執行一次(表達式的真值在每次循環結束後檢查),然而在正規的
while
循環中就不一定了(表達式真值在循環開始時檢查,如果一開始就為
FALSE
則整個循環立即終止)。
c語言do while循環語句舉例
這篇文章主要給大家介紹了關於C語言中do-while語句的2種寫法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧
while循環和for循環都是入口條件循環,即在循環的每次迭代之前檢查測試條件,所以有可能根本不執行循環體中的內容。C語言還有出口條件循環(exit-condition loop),即在循環的每次迭代之後檢查測試條件,這保證了至少執行循環體中的內容一次。這種循環被稱為do while循環。
看下面的例子:
#include stdio.h
int main(void)
{
const int secret_code = 13;
int code_entered;
do
{
printf(“To enter the triskaidekaphobia therapy club,\n”);
printf(“please enter the secret code number: “);
scanf(“%d”, code_entered);
} while (code_entered != secret_code);
printf(“Congratulations! You are cured!\n”);
return 0;
}
運行結果:
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 12
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 14
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 13
Congratulations! You are cured!
使用while循環也能寫出等價的程序,但是長一些,如程序清單6.16所示。
#include stdio.h
int main(void)
{
const int secret_code = 13;
int code_entered;
printf(“To enter the triskaidekaphobia therapy club,\n”);
printf(“please enter the secret code number: “);
scanf(“%d”, code_entered);
while (code_entered != secret_code)
{
printf(“To enter the triskaidekaphobia therapy club,\n”);
printf(“please enter the secret code number: “);
scanf(“%d”, code_entered);
}
printf(“Congratulations! You are cured!\n”);
return 0;
}
在C語言中,while 和do while的死循環例子
一般在運行循環語句的時候,會保證判斷條件一直在做改變,所以在某個時刻導致條件為假而退出循環。
如:
int n=10;
while(n–) //當n–為0的時候退出循環
{
printf(“n=[%d]\n”);
}
而死循環,就是由於人為編寫失誤或程序需要導致循環條件一直為真,這樣程序會永遠執行循環中的語句,如:
int n=10;
while(n++) //此時n++永遠不等於0,則條件永遠為真,死循環
{
printf(“n=[%d]\n”);
}
c語言do while語句有哪些?
先做do輸出1,然後判斷while條件是否滿足,!(–x),此時x=1,然後自減,x=0,非零滿足條件,循環,輸出-2,然後又判斷while條件,此時不滿足條件,x=-2,自減,x=-3,非一次,為0,跳出循環,所以此時輸出結果為1,2。
mian()
{char=123;
do
{printf(“%c”,x%10+’0′);
}while(x/=10);
}
編譯並執行後,屏幕顯示:
nu=20100
在程序中,for語句小括號內的三個表達式分別為:n=1;n=200;n++。表達式1,n=1是給n賦初值,表達式2是關係表達式,n小於等於200時,表達式都為真,則執行循環體內的語句nu+=n;(即nu=nu+n;),然後執行表達式3(n++),進入下一輪循環;若n大於200時,表達式2為假,則終止循環,執行printf()語句,在屏幕上打印出:nu=20100。
以上內容參考:百度百科-循環語句
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/291764.html