# C# 自主學習 ###### tags: `C#` `alogrithm` > 學習內容:Array、Recursion ## **Ch1. Array** ### 1. 宣告 + 初始化 ```csharp <DataType>[] ArrayName = new <DataType>[size] <DataType>[] ArrayName = {} // Example int[] A = new int[10] string[] B = new string[10] char[] C = new char[10] //another way int[] A = {10 , 20 , 30} string[] B = {"Hello" , "world" , "i love you"} char[] C = {'A' , 'B' , 'C'} ``` :::info :bulb: Array 中第一個元素的編號為 0 ::: ```csharp= int[] A = {10 , 20 , 30} int[] B = A ``` >此時 B 儲存的是 A 的記憶體位置,同時指到一個陣列 ### 2. foreach 用法 ```csharp= int[] A = {10 , 20 , 30} foreach(int element in A){ Console.WriteLine(element); // 10 20 30; } ``` :::info :bulb: foreach 可以走遍 Array 中的每一個元素 ::: ### 3. Array 類別的工具 #### (1) 排序 (Sort) ```csharp= int[] A = {20, 30, 10} Array.sort(A) // A = {10 , 20 , 30} ``` #### (2) 反轉 (Reverse) ```csharp= int[] A = {10 , 20 , 30} Array.Reverse(A) // A = {30 , 20 , 10} ``` :::info :bulb: Length 可以取 Array 的長度 ::: ### 4. Leetcode 練習題 #### 27. Remove Element (easy) >Solution ```csharp= public class Solution { public int RemoveElement(int[] nums, int val) { int ans = 0; //宣告一個計數器 for(int i = 0; i < nums.Length; i++){ if(nums[i] == val){ nums[i] = -1; //將要刪除的元素設定為 -1 }else{ ans++; //計數器+1 } } int[] nums2 = new int[nums.Length]; int a = 0; for(int i = 0; i < nums.Length; i++){ if(nums[i] == -1){ continue; }else{ nums2[a] = nums[i]; // nums2 是刪除不要的元素後的新陣列 a++; } } for(int i = 0; i < nums.Length; i++){ nums[i] = nums2[i]; // 複製num2 到 nums } return ans; // 回傳計數器 } } ``` >Result ![](https://i.imgur.com/3SweVVf.png) ## **Ch2. Recursion** ### 1. Interation、Recursion ```csharp= //Interation int a = 1; int Sum(int a) { for(int i = 0; i < 9; i++) { a = a + (i+2); } return a; } //Recursion int count = 0; int Demo(int a){ if(count == 10){ return a; }else{ count++; a *= 2; return Demo(a); } } ```