1. 程式人生 > 其它 >C#學習筆記,2021/12/9

C#學習筆記,2021/12/9

for迴圈語句 for語句 for(初始表示式;條件表示式;增量表達式 ) { 迴圈體程式碼; } 注意 初始表示式:宣告迴圈變數,機率迴圈的次數[int i=1] 條件表示式:迴圈的條件;[i<=10] 增量表達式:改變迴圈條件的程式碼,使迴圈程式碼終有一天不在成立;[i++] 執行過程:
  1. 程式首先執行“初始表示式”,宣告一個迴圈變數,用來記錄迴圈的次數;然後執行“條件表示式”,判斷迴圈條件是否成立,如果“條件表示式”返回的結果為ture,則執行迴圈程式碼體。
  2. 當執行玩迴圈程式碼後,執行“增量表達式”,然後再次執行“條件表示式”,繼續判斷迴圈條件是否成立,如果成立則繼續迴圈程式碼題,如果不成立,則跳出for迴圈結構。
程式碼入下: for (int i = 0; i < 10; i++)
{
Console.WriteLine("heheheheheh{0}",i);
}
Console.ReadKey(); 輸出結果: heheheheheh0
heheheheheh1
heheheheheh2
heheheheheh3
heheheheheh4
heheheheheh5
heheheheheh6
heheheheheh7
heheheheheh8
heheheheheh9 演示:1+2+3+.....+100之和。 程式碼入下: int sum = 0;
for (int i = 0; i <=100; i++)
{
sum += i;
}
Console.WriteLine(sum);
Console.ReadKey(); 程式碼輸出結果為5050 作業:列印1到10 for (int i = 1; i <=10; i++)
{
Console.WriteLine(i);
}
Console.ReadKey(); 作業:計算1到100所有奇數的和,再計算所有偶數的和。 奇數和: int sum = 0;
for (int i = 1; i <=100; i+=2)
{
sum+=i;
}
Console.WriteLine(sum);
Console.ReadKey(); 結果2500 偶數和 : int sum = 0;//計算偶數和
for (int i = 2; i <=100; i+=2)
{
sum += i;
}
Console.WriteLine(sum);
Console.ReadKey(); 結果2550