iT邦幫忙

3

【C#學習筆記】02《陣列與迴圈》

  • 分享至 

  • xImage
  •  

本篇主要紀錄陣列及迴圈的基本使用方式,包括 for、foreach、while 及 do-while,以及控制迴圈的 continue、break。透過這些基礎語法,可以有效地處理多筆資料與重複性邏輯,是撰寫程式時不可或缺的核心能力。

陣列在程式中是個很重要的元素,它提供了一種能夠以結構化方式儲存多個相同型別資料的手段,使資料的管理與存取更加直觀且高效,搭配迴圈使用時,能夠快速地遍歷與操作整個資料集合,進一步提升程式的可讀性維護性


【C#學習筆記】01《快速入門筆記》
【C#學習筆記】03《函式》


陣列

以下僅提供基本陣列寫法,尚未提及動態集合(如List),在未來的章節會補充說明。

int[] a = new int[3];//Default 0, 0, 0
int[] a1 = new int[] { 1, 2, 3 };

int[] b = { 1, 2, 3 };
int[] c = [1, 2, 3];//Support from C# 12(.Net 8)

Console.WriteLine($"c's length = {c.Length}");
Console.WriteLine($"{c[2]}");
Console.WriteLine($"{c[3]}");//Error: IndexOutOfRangeException

string[] d =
    [
    "Kevin",
    "Bob",
    "Alice"
    ];

//二維陣列two-dimensional array
int[,] e ={{1, 2, 3},{4, 5, 6}};//length need to consistancy

Console.WriteLine($"{e[0,0]}");//1
Console.WriteLine($"{e[1,2]}");//6

//散佈運算spread element //Support from C# 12(.Net 8) 
int[] row1 = [1, 2, 3];
int[] row2 = [4, 5, 6];
int[] row3 = [7, 8, 9];

int[] singleArray = [.. row1, .. row2, .. row3];//[1, 2, 3, 4, 5, 6, 7, 8, 9]
Console.WriteLine($"singleArray[4]:{singleArray[4]}");//singleArray[4]:5

迴圈(for)

for (int i = 0; i < 10; i++)
{
    Console.WriteLine($"i = {i}");//0,1,2,3,4,5,6,7,8,9
}
Console.WriteLine();

for (int i = 0; i < 10; i+=2)
{
    Console.WriteLine($"i = {i}");//0,2,4,6,8
}
Console.WriteLine();

int[] a = [1, 2, 3, 4, 5];
for (int i = 0;i < a.Length;i++)//a.Length=5
{
    Console.WriteLine($"a{i} = {a[i]}");//a0=1,a1=2,a2=3,a3=4,a4=5
}
Console.WriteLine();

//巢狀迴圈
for (int i = 1; i < 10; i++)//multiplication table
{
    for (int j = 1; j < 10; j++)
    {
        Console.WriteLine($"{i} * {j} = {i * j}");
    }
    Console.WriteLine();
}
Console.WriteLine();

控制迴圈(contiune & break)

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine("print");
    if (i % 2 == 0) continue;// skip the rest of the loop body when i is even
    Console.WriteLine(i);
    
}
Console.WriteLine();

for (int i = 1; i <= 10; i++)
{
    if (i % 5 == 0) break;// exit the loop when i is a multiple of 5
    Console.WriteLine(i);
    
}

迴圈(foreach)

int[] a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
foreach (var item in a)//against the array a,iterating through each element and printing it to the console
{
    Console.WriteLine(item);
}
Console.WriteLine();

string[] items =
[
"aaa",
"bbb",
"ccc",
"ddd",
"eee",
];
foreach (var item in items)
{
    if(item.Contains("c"))continue;
    if(item.Contains("d"))break;
    Console.WriteLine(item);
}
Console.WriteLine();

迴圈(while)

int i = 0;
while(i < 10)
{
    Console.WriteLine(i);
    i++;//control while loop
}

Console.WriteLine();
int[] a =  new int[10];
i = 0;
while (i < a.Length)
{
    Console.WriteLine($"a[{i}] = {a[i]}");
    i++;
}

Console.WriteLine();
int[] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
i = 0;
while (true)
{
    if (i >= b.Length) break;
    if (i % 2 == 1) b[i] += 10;
    Console.WriteLine(i);
    i++;
}
for (int j = 0; j < b.Length; j++)
{
    Console.WriteLine($"b[{j}] = {b[j]}");
}

迴圈(do-while)

int[] a = new int[10];
int i = 0;
do
{
    a[i]+= i;
    Console.WriteLine($"a[{i}] = {a[i]}");
    i++;
} while (i < a.Length);
Console.WriteLine();

do
{
    Console.Write("Please enter a string: ");
    var input = Console.ReadLine();
    if ( input != null )Console.WriteLine(input);
    if (input == "q") break;
} while (true);
Console.WriteLine();

在程式設計中,迴圈(Loop)用於重複執行特定區塊的程式碼,而不同種類的迴圈在使用情境與控制方式上各有差異。

首先,for 迴圈適合用於「已知執行次數」的情境。它將初始化、條件判斷與遞增(或遞減)寫在同一行,結構清晰且集中。例如,當需要依序存取陣列中的每個元素時,for迴圈能明確控制索引位置,具有高度彈性。

相較之下,foreach 迴圈則專注於「逐一遍歷集合(Collection)」。它不需要手動管理索引,因此語法更簡潔,也較不容易出錯。然而,foreach 通常不適合需要修改集合內容或依賴索引操作的情況,其重點在於讀取資料非控制流程

while迴圈則適用於「執行次數不確定」的情境,只要條件成立就會持續執行。這使得while在處理例如使用者輸入、等待特定條件發生等情況時特別有用。不過,若條件設計不當,可能會導致無限迴圈,因此需要特別注意終止條件。

最後,do-while 迴圈與 while 類似,但差別在於它會「先執行一次,再進行條件判斷」。這表示即使條件一開始不成立,程式區塊仍會至少執行一次,適合用於需要先執行操作再決定是否繼續的場景,例如選單或驗證流程

總結而言,for強調結構與控制,foreach著重於簡潔遍歷,while提供彈性的條件控制,而do-while則確保至少執行一次。理解這些差異,有助於在不同情境下選擇最合適的迴圈,寫出更清晰且可靠的程式碼。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言