C#-循環語句(六)
阿新 • • 發佈:2018-09-08
數組 image 分享 如果 while循環 上海 con read foreach 然後將取出的數據賦給變量,每一次賦值後,運行一次循環
for循環
格式:
for(表達式1;循環條件;表達式2)
{
循環體;
}
解釋:先執行表達式1,再判斷循環條件是否為真,如果為真則執行循環體,執行完成後再執行表達式2
再次判斷循環條件,由此一直反復循環,直到循環條件為假,退出循環
表達式1只在循環開始的時候執行一次
示例
1 using System; 2 3 namespace Loops 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { /*for 循環執行 */ 9 for (int a = 1; a < 5; a = a + 1) 10 { 11 Console.WriteLine("a 的值: {0}", a); 12 } 13 Console.ReadLine(); 14 } 15 } 16 }
結果
foreach 循環
格式:
foreach(數據類型 變量 in 數組或集合)
{
循環體;
}
解釋:從數組或集合中依次取出每一項的數據
示例
1 using System; 6 7 namespace Loops 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 string[] citys = new string[] { "北京", "上海", "廣州", "北京", "西安" }; 14 foreach (string city in citys)15 { 16 System.Console.WriteLine(city); 17 } 18 System.Console.WriteLine("循環結束"); 19 } 20 } 21 }
結果
while循環
格式:
while(循環條件)
{
循環體;
}
解釋:如果循環條件為真則執行循環體
執行完循環體之後,再判斷條件是否為真,如果為真則繼續執行循環體
直到循環條件為假,退出循環
do...while循環
格式:
do
{
循環體;
}
while (循環條件)
解釋:與while執行順序相反,while是先判斷條件然後執行循環體,do...while是先執行一次循環體然後進行循環條件的判斷
如果滿足則再執行循環體,直到條件不滿足,退出循環
示例
1 using System; 2 3 namespace Loops 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 int a = 1; 10 do 11 { 12 Console.WriteLine("a 的值: {0}", a); 13 a = a + 1; 14 } while (a < 5); 15 16 System.Console.WriteLine("循環結束"); 17 } 18 } 19 }
結果
C#-循環語句(六)