C # array,
An array is a data structure that can contain multiple elements of the same type. array elements in C # Start from scratch.
Arrays can be divided into simple arrays, multi-dimensional arrays, and sawtooth arrays.
Simple Array
1. Declaration and initialization
int [] x = new int[5];
After declaring the array, you must allocate memory to the array to save the elements of the array. The array is of the reference type, so it must be allocated with a pushed memory. Use the new operator to specify the type and quantity of elements in the array to initialize the variable of the array.
1. assign values to each element of the array using the array Initiator
int [] x = new int[5]{10,6,7,15,8};
2. the array size is not specified.
int [] x = new int[]{10,6,7,15,8};
3. Simplified Form
int [] x = {10,6,7,15,8};
2. Access array elements
1. Use the indexer to pass element numbers to access the Array
int [] x = {10,6,7,15,8};Console.WriteLine(x[0]); // 10Console.WriteLine(x[1]); // 6
2. Use For loop Traversal
int[] x = { 10, 6, 7, 15, 8 };for (int i = 0; i < x.Length; i++){ Console.Write(x[i]+" "); // 10 6 7 15 8}
3. Use foreach for loop Traversal
int[] x = { 10, 6, 7, 15, 8 };foreach (var i in x){ Console.Write(i + " "); // 10 6 7 15 8 }
4. Sort by Array. Sort
int[] x = { 10, 6, 7, 15, 8 };Array.Sort(x); foreach (var i in x){ Console.Write(i + " "); // 6 7 8 10 15}
5. Typical question: Bubble Sorting
int[] array = { 10, 6, 7, 15, 8 };int temp = 0;for (int i = 0; i < array.Length - 1; i++){ for (int j = i + 1; j < array.Length; j++) { if (array[j] < array[i]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } }}foreach (var i in array){ Console.Write(i + " "); // 6 7 8 10 15}
Multi-dimensional array
Multi-dimensional arrays are indexed by two or more integers.
1. Two-dimensional array declaration and initialization
int[,] y1 = new int[2, 2];y[0, 0] = 1;y[0, 1] = 2;y[1, 0] = 3;y[1, 1] = 4;
int[,] y2 = { { 1, 2 }, { 3, 4 } };
2. 3D Array
int[,,] y3 ={ {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}, {{9, 10}, {11, 12}},};
Sawtooth Array
The two-dimensional array is a complete rectangle, while the size of the Sawtooth array is flexible. In the Sawtooth array, each row can have different sizes.
int[][] j = new int[3][];j[0] = new int[2] { 1, 2 };j[1] = new int[5] { 3, 4, 5, 6, 7 };j[2] = new int[3] { 8, 9, 10 };