二級考試:學(xué)點C語言(while與dowhile循環(huán))

字號:

1. while 循環(huán):
    #include 
    int main(void)
    {
    int i=0;
    while (i<10) {
    i++;
    printf("%d ", i);
    } 
    getchar();
    return 0;
    }
    2. do while 循環(huán):
    #include 
    int main(void)
    {
    int i=0;
    do
    {
    i++;
    printf("%d ", i);
    } while (i<10);
    getchar();
    return 0;
    }
    3. while 與 do while 的區(qū)別:
    #include 
    int main(void)
    {
    int i=10;
    while (i<10)
    {
    printf("while");  //這個不會執(zhí)行
    }
    do
    {
    printf("do while"); //這個會執(zhí)行
    } while (i<10);
    getchar();
    return 0;
    }
    4. break 與 continue:
    #include 
    int main(void)
    {
    int i=0;
    while (i<10)
    {
    i++;
    if (i == 8) break;   /* 不超過 8 */
    if (i%2 == 0) continue; /* 只設(shè)為首頁要單數(shù) */
    printf("%d ", i);
    }
    getchar();
    return 0;
    }
    5. 無限循環(huán):
    #include 
    int main(void)
    {
    int i=0;
    while (1)  //或 while (!0)
    {
    i++;
    printf("%d ", i);
    if (i == 100) break;
    }
    getchar();
    return 0;
    }