中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

C 嵌套循環(huán)

C 循環(huán) C 循環(huán)

C 語言允許在一個循環(huán)內(nèi)使用另一個循環(huán),下面演示幾個實(shí)例來說明這個概念。

語法

C 語言中 嵌套 for 循環(huán) 語句的語法:

for (initialization; condition; increment/decrement)
{
    statement(s);
    for (initialization; condition; increment/decrement)
    {
        statement(s);
        ... ... ...
    }
    ... ... ...
}

流程圖:

C 語言中 嵌套 while 循環(huán) 語句的語法:

while (condition1)
{
    statement(s);
    while (condition2)
    {
        statement(s);
        ... ... ...
    }
    ... ... ...
}

流程圖:

C 語言中 嵌套 do...while 循環(huán) 語句的語法:

do
{
    statement(s);
    do
    {
        statement(s);
        ... ... ...
    }while (condition2);
    ... ... ...
}while (condition1);

流程圖:

關(guān)于嵌套循環(huán)有一點(diǎn)值得注意,您可以在任何類型的循環(huán)內(nèi)嵌套其他任何類型的循環(huán)。比如,一個 for 循環(huán)可以嵌套在一個 while 循環(huán)內(nèi),反之亦然。

實(shí)例

下面的程序使用了一個嵌套的 for 循環(huán)來查找 2 到 100 中的質(zhì)數(shù):

for 嵌套實(shí)例

#include <stdio.h> int main () { /* 局部變量定義 */ int i, j; for(i=2; i<100; i++) { for(j=2; j <= (i/j); j++) if(!(i%j)) break; // 如果找到,則不是質(zhì)數(shù) if(j > (i/j)) printf("%d 是質(zhì)數(shù)n", i); } return 0; }

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

2 是質(zhì)數(shù)
3 是質(zhì)數(shù)
5 是質(zhì)數(shù)
7 是質(zhì)數(shù)
11 是質(zhì)數(shù)
13 是質(zhì)數(shù)
17 是質(zhì)數(shù)
19 是質(zhì)數(shù)
23 是質(zhì)數(shù)
29 是質(zhì)數(shù)
31 是質(zhì)數(shù)
37 是質(zhì)數(shù)
41 是質(zhì)數(shù)
43 是質(zhì)數(shù)
47 是質(zhì)數(shù)
53 是質(zhì)數(shù)
59 是質(zhì)數(shù)
61 是質(zhì)數(shù)
67 是質(zhì)數(shù)
71 是質(zhì)數(shù)
73 是質(zhì)數(shù)
79 是質(zhì)數(shù)
83 是質(zhì)數(shù)
89 是質(zhì)數(shù)
97 是質(zhì)數(shù)

while 嵌套實(shí)例

#include <stdio.h> int main() { int i=1,j; while (i <= 5) { j=1; while (j <= i ) { printf("%d ",j); j++; } printf("n"); i++; } return 0; }

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

do-while 嵌套實(shí)例

#include <stdio.h> int main() { int i=1,j; do { j=1; do { printf("*"); j++; }while(j <= i); i++; printf("n"); }while(i <= 5); return 0; }

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

*
**
***
****
*****

C 循環(huán) C 循環(huán)

其他擴(kuò)展