藍鷗(www.lanou3g.com)是一家集產(chǎn)、學其监、研、創(chuàng)為一體的綜合性移動互聯(lián)網(wǎng)研發(fā)培訓機構(gòu)限匣,致力于iOS開發(fā)抖苦、Unity3D游戲開發(fā)、Android開發(fā)膛腐、HTML5前端開發(fā)和Web安全攻防等技術(shù)人才的培養(yǎng)睛约。
一、循環(huán)結(jié)構(gòu)
循環(huán)結(jié)構(gòu)-條件滿足時哲身,反復(fù)執(zhí)行同一個語句塊
循環(huán)結(jié)構(gòu)的作用是重復(fù)執(zhí)行一段代碼
循環(huán)結(jié)構(gòu)是有條件的辩涝,循環(huán)次數(shù)是有限的
二、While循環(huán)語法
“當”條件表達式成立時勘天,會執(zhí)行循環(huán)體
While(條件表達式){
循環(huán)體……
}
舉例說明:如果用戶輸入負數(shù)程序結(jié)束怔揩,如果用戶輸入的不是負數(shù),程序會一直執(zhí)行脯丝,提示用戶輸入一個負數(shù)商膊。
usingSystem;
namespaceLesson13
{
classMainClass
{
publicstaticvoidMain(string[]args)
{
inta=int.Parse(Console.ReadLine());
while(a>=0){
Console.WriteLine("請輸入一個負數(shù)");
a=int.Parse(Console.ReadLine());
}
}
}
}
三、Break
之前在學習switch語句的時候宠进,有接觸到break
在switch語句中晕拆,break用于跳出switch語句
在循環(huán)語句中,break用于跳出整個循環(huán)
Break在循環(huán)中通常與if連用
舉例:用戶輸入負數(shù)程序結(jié)束材蹬,如果用戶輸入的不是負數(shù)实幕,程序會一直執(zhí)行,提示用戶輸入一個負數(shù)堤器。如果程序輸入的是100昆庇,程序也會結(jié)束!
usingSystem;
namespaceLesson13
{
classMainClass
{
publicstaticvoidMain(string[]args)
{
inta=int.Parse(Console.ReadLine());
while(a>=0){
if(a==100){
//跳出整個循環(huán),繼續(xù)執(zhí)行循環(huán)體下面的其他代碼
break;
}
Console.WriteLine("請輸入一個復(fù)數(shù)");
a=int.Parse(Console.ReadLine());
}
}
}
}
四闸溃、continue——結(jié)束本輪循環(huán)整吆,進行下一輪循環(huán)
在循環(huán)語句中,結(jié)束本輪循環(huán)辉川,進入下輪循環(huán)
Continue后面的代碼不在執(zhí)行表蝙,通常與if連用
舉例說明:
inti=0;
while(i<100){
i++;
if(i%7!=0){
//跳出本輪循環(huán),繼續(xù)執(zhí)行下一輪循環(huán)
continue;
}
Console.WriteLine(i);
}
五乓旗、do……while循環(huán)語句
do{
循環(huán)體
}While(條件表達式)府蛇;
Do……while和while循環(huán)的區(qū)別在于;
Do……while循環(huán)至少會執(zhí)行一遍循環(huán)體
舉例說明:
inti=1;
do{
Console.WriteLine(i);
i++;
}while(i<=100);
Do……while 和while的區(qū)別就是do……while至少會執(zhí)行一次循環(huán)體寸齐,而while循環(huán)中可以一遍都不執(zhí)行的情況欲诺!
舉例說明:Do……while 和while的區(qū)別
inti=0;
while(i>100){
Console.WriteLine("while");
}
do{
Console.WriteLine("dowhile");
}while(i>100);
源代碼:
usingSystem;
namespaceLesson13
{
classMainClass
{
publicstaticvoidMain(string[]args)
{
//inta=int.Parse(Console.ReadLine());
//while(a>=0){
//if(a==100){
//跳出整個循環(huán),繼續(xù)執(zhí)行循環(huán)體下面的其他代碼
//break;
//}
//Console.WriteLine("請輸入一個負數(shù)");
//a=int.Parse(Console.ReadLine());
//}
//inti=0;
//while(i<100){
//i++;
//if(i%7!=0){
//跳出本輪循環(huán)渺鹦,繼續(xù)執(zhí)行下一輪循環(huán)
//continue;
//}
//Console.WriteLine(i);
//}
//inti=1;
//do{
//Console.WriteLine(i);
//i++;
//}while(i<=100);
inti=0;
while(i>100){
Console.WriteLine("while");
}
//dowhile至少會執(zhí)行一遍循環(huán)體
do{
Console.WriteLine("dowhile");
}while(i>100);
}
}
}