C語言入門之循環(huán)結構

字號:

循環(huán)結構是程序中一種很重要的結構。其特點是, 在給定條件成立時,反復執(zhí)行某程序段,直到條件不成立為止。 給定的條件稱為循環(huán)條件,反復執(zhí)行的程序段稱為循環(huán)體。 C語言提供了多種循環(huán)語句,可以組成各種不同形式的循環(huán)結構。
     while語句
     while語句的一般形式為: while(表達式)語句; 其中表達式是循環(huán)條件,語句為循環(huán)體。
     while語句的語義是:計算表達式的值,當值為真(非0)時, 執(zhí)行循環(huán)體語句。其執(zhí)行過程可用圖3—4表示。 統(tǒng)計從鍵盤輸入一行字符的個數。
    #include
    void main(){
    int n=0;
    printf("input a string:\n");
    while(getchar()!='\n') n++;
    printf("%d",n);
    } int n=0;
    printf("input a string:\n");
    while(getchar()!='\n')
    n++;
    printf("%d",n);
     本例程序中的循環(huán)條件為getchar()!='\n',其意義是, 只要從鍵盤輸入的字符不是回車就繼續(xù)循環(huán)。循環(huán)體n++完成對輸入字符個數計數。從而程序實現了對輸入一行字符的字符個數計數。
     使用while語句應注意以下幾點:
     1.while語句中的表達式一般是關系表達或邏輯表達式,只要表達式的值為真(非0)即可繼續(xù)循環(huán)。 來源:www.examda.com 
    void main(){
     int a=0,n;
     printf("\n input n: ");
     scanf("%d",&n);
     while (n--)
     printf("%d ",a++*2);
    } int a=0,n;
    printf("\n input n: ");
    scanf("%d",&n);
    while (n--)
    printf("%d ",a++*2);
     本例程序將執(zhí)行n次循環(huán),每執(zhí)行一次,n值減1。循環(huán)體輸出表達式a++*2的值。該表達式等效于(a*2;a++)
     2.循環(huán)體如包括有一個以上的語句,則必須用{}括起來, 組成復合語句。