C語言程序設(shè)計初步

字號:

循環(huán)結(jié)構(gòu)程序
    循環(huán)結(jié)構(gòu)是程序中一種很重要的結(jié)構(gòu)。其特點(diǎn)是, 在給定條件成立時,反復(fù)執(zhí)行某程序段,直到條件不成立為止。 給定的條件稱為循環(huán)條件,反復(fù)執(zhí)行的程序段稱為循環(huán)體。 C語言提供了多種循環(huán)語句,可以組成各種不同形式的循環(huán)結(jié)構(gòu)。
     while語句
    while語句的一般形式為: while(表達(dá)式)語句; 其中表達(dá)式是循環(huán)條件,語句為循環(huán)體。
    while語句的語義是:計算表達(dá)式的值,當(dāng)值為真(非0)時, 執(zhí)行循環(huán)體語句。其執(zhí)行過程可用圖3—4表示。 統(tǒng)計從鍵盤輸入一行字符的個數(shù)。
    #include
    void main(){
    int n=0;
    printf("input a string: ");
    while(getchar()!=’ ’) n++;
    printf("%d",n);
    } int n=0;
    printf("input a string: ");
    while(getchar()!=’ ’)
    n++;
    printf("%d",n);
    本例程序中的循環(huán)條件為getchar()!=’ ’,其意義是, 只要從鍵盤輸入的字符不是回車就繼續(xù)循環(huán)。循環(huán)體n++完成對輸入字符個數(shù)計數(shù)。從而程序?qū)崿F(xiàn)了對輸入一行字符的字符個數(shù)計數(shù)。
    使用while語句應(yīng)注意以下幾點(diǎn):
    1.while語句中的表達(dá)式一般是關(guān)系表達(dá)或邏輯表達(dá)式,只要表達(dá)式的值為真(非0)即可繼續(xù)循環(huán)。
    void main(){
    int a=0,n;
    printf(" input n: ");
    scanf("%d",&n);
    while (n--)
    printf("%d ",a++*2);
    } int a=0,n;
    printf(" input n: ");
    scanf("%d",&n);
    while (n--)
    printf("%d ",a++*2);
    本例程序?qū)?zhí)行n次循環(huán),每執(zhí)行一次,n值減1。循環(huán)體輸出表達(dá)式a++*2的值。該表達(dá)式等效于(a*2;a++)
    2.循環(huán)體如包括有一個以上的語句,則必須用{}括起來, 組成復(fù)合語句。
    3.應(yīng)注意循環(huán)條件的選擇以避免死循環(huán)。
    void main(){
    int a,n=0;
    while(a=5)
    printf("%d ",n++);
    } int a,n=0;
    while(a=5)
    printf("%d ",n++);
    本例中while語句的循環(huán)條件為賦值表達(dá)式a=5, 因此該表達(dá)式的值永遠(yuǎn)為真,而循環(huán)體中又沒有其它中止循環(huán)的手段, 因此該循環(huán)將無休止地進(jìn)行下去,形成死循環(huán)。4.允許while語句的循環(huán)體又是while語句,從而形成雙重循環(huán)。