C # The declaration and traversal of the Sawtooth array (array ),
1. What is a sawtooth array?
The number of elements in each row in the array is different.
2. Declare a sawtooth array.
Declare an array. Its Syntax mainly defines multiple square brackets in the array declaration, such:
Int [] [] ArrayName;
The number of rows in the array is set in the first bracket pair, and the second bracket defines the number of elements in each row. It is set to null first. The number of elements in each row is not equal.
There are also the following statements:
Initialize an array (also called a sub-array) that contains other arrays, and then initialize the sub-array in sequence.
ArrayName = new int[2][]; ArrayName = new int[3]; ArrayName = new int[4];
Improved form of Literal Value assignment:
ArrayName = new int[3][] { new int[] {1,2,3},new int{1}; new int{4,5} };
You can also simplify it by placing the initial value and declaration of the array on the same row, as shown below:
int[][] ArrayName = {new int[] {1,2,3}, new int{1}; new int{4,5}};
3. The for loop and foreach methods can be used to traverse the Sawtooth array.
For Loop: uses two for loops to traverse arrays one by one. for more information, see the code.
Foreach: it also uses nested methods to obtain actual data.
Why is nesting required? Because the array myIntArray4 contains the int [] element rather than the int element, the subarray and the array itself must be iterated.
Static void Main (string [] args) {// declare a three-line int [] [] myIntArray4; myIntArray4 = new int [3] []; myIntArray4 [0] = new int [] {1, 11,111}; myIntArray4 [1] = new int [] {2, 22 }; myIntArray4 [2] = new int [] {3, 33,333,333 3}; for (int I = 0; I <myIntArray4.Length; I ++) {for (int j = 0; j <myIntArray4 [I]. length; j ++) {Console. writeLine ("{0}", myIntArray4 [I] [j]);}/* for Loop */foreach (int [] AB in myIntArray4) {foreach (int abc in AB) {Console. writeLine (abc);}/* foreach */} Console. read ();}