C 教程
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),反之亦然。
下面的程序使用了一個嵌套的 for 循環(huán)來查找 2 到 100 中的質(zhì)數(shù):
當(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ù)
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
* ** *** **** *****其他擴(kuò)展