do...while循環(huán)與while循環(huán)相同,只是 do...while 循環(huán)至少執(zhí)行一次代碼塊。
語(yǔ)法:
do { //代碼塊 } while(condition);
do...while循環(huán)以do關(guān)鍵字開(kāi)始,后跟代碼塊和帶有while關(guān)鍵字的布爾表達(dá)式。當(dāng)布爾條件的計(jì)算結(jié)果為false時(shí),do while循環(huán)停止執(zhí)行。因?yàn)閣hile(condition)在塊的末尾指定,它肯定至少執(zhí)行一次代碼塊。
int i = 0; do { Console.WriteLine("i = {0}", i); i++; } while (i < 5);
i = 0 i = 1 i = 2 i = 3 i = 4
在循環(huán)外指定初始化,在 do...while 循環(huán)內(nèi)指定遞增/遞減計(jì)數(shù)器。
使用 break 或 return退出do while循環(huán)。
int i = 0; do { Console.WriteLine("i = {0}", i); i++; if (i > 5) break; } while (i < 10);
i = 0 i = 1 i = 2 i = 3 i = 4 i = 5
do-while循環(huán)可在另一個(gè)do-while循環(huán)內(nèi)使用。
int i = 0; do { Console.WriteLine("Value of i: {0}", i); int j = i; i++; do { Console.WriteLine("Value of j: {0}", j); j++; } while (j < 2); } while (i < 2);
輸出:
i = 0 j = 0 j = 1 i = 1 j = 1