閱讀Stephens' C#教材第十九章筆記
Chapter 19 Repeaing Program Steps.
本章將學習如何讓程式重複執行,也就是所謂迴圈。
主要介紹四種迴圈程式:For Loop, ForEach Loop, While Loops, Do Loop。請詳細的資料可參考微軟網頁
Sum程式示範For Loop用來計算由1加到目標值的總和
// Calculate 1 + 2 + ... + N.
private void calculateButton_Click(object sender, EventArgs e)
{
// Get the input number.
long n = long.Parse(numberTextBox.Text);
// Calculate the sum.
long total = 0;
for (int i = 1; i <= n; i++)
{
total += i;
}
// Display the result.
resultTextBox.Text = total.ToString("#,##0");
}
Fibonacci程式示範For Loop用來計算費波那西數列
// Calculate the Fibonacci number.
private void calculateButton_Click(object sender, EventArgs e)
{
// Get the input value.
long n = long.Parse(numberTextBox.Text);
// Initialize the base cases.
long fibo1 = 0; // Initially Fibonacci(0).
long fibo2 = 1; // Initially Fibonacci(1).
long fiboN = 0; // Initially Fibonacci(0).
// Calculate the result.
for (int i = 0; i < n; i++)
{
// Calculate fiboN from fibo1 and fibo2.
fiboN = fibo1 + fibo2;
// Update fibo1 and fibo2 for the next loop.
fibo2 = fibo1;
fibo1 = fiboN;
}
resultTextBox.Text = fiboN.ToString("#,##0");
}
MinMaxAverage程式示範Foreach Loop用來計算所有輸入值的最大最小及平均值
// Add an item to the list and calculate
// the minimum, maxiumu, and average.
private void addButton_Click(object sender, EventArgs e)
{
// Add the new number to the list.
scoresListBox.Items.Add(int.Parse(scoreTextBox.Text));
scoreTextBox.Clear();
scoreTextBox.Focus();
// Find the minimum and maximum,
// and add up the scores.
float total = 0;
int minimum = (int)scoresListBox.Items[0];
int maximum = (int)scoresListBox.Items[0];
foreach (int score in scoresListBox.Items)
{
total += score;
if (score < minimum) minimum = score;
if (score > maximum) maximum = score;
}
// Calculate the average.
float average = total / scoresListBox.Items.Count;
// Display the results.
minimumTextBox.Text = minimum.ToString();
maximumTextBox.Text = maximum.ToString();
averageTextBox.Text = average.ToString("0.00");
}
AddOrderItems程式示範巢狀Foreach Loop用來計算所有輸入物品的合計
MakeWord程式示範巢狀Foreach Loop用來 產生A, B, C, D四字的變化組合
GCD程式示範用do loop用來算出最大公因數
PrimeFactors程式示範用for loop及while loop用來算出某一數字的質數組合
TRY IT中示範如何設計出Login表單,使用while loop及if敘述判斷登錄帳號密碼是否正確