(Tutorial C # array 2) differences between array attributes, foreach traversal, and staggered arrays and rectangular Arrays

Source: Internet
Author: User
Tags array definition

In this lesson, we will learn the attributes of arrays, the usage of foreach, And the staggered array I mentioned in the previous lesson, I will explain the differences between the staggered array definition and the rule two-dimensional array (rectangular array) through multiple examples, in the next section, we will also learn the common methods of arrays.

Next, let's take a look at the attributes of arrays. What are attributes? In the future, I will give you a detailed explanation of the class. Now I will give you an example of real life to help you understand what attributes are. attributes are generally nouns, represents the characteristics of its owner (that is, the object), suchColor, size (attribute ),In the next section, the learning array method is generally a verb, such as the rag function,Dishcloth (object) cleanup (method) desktop, vehicle, ground (the object of these actions can also be compared to the parameters to be learned in the future ),Now rememberAn Attribute describes the characteristics of an object. It is generally a noun.,The method is to describe the object function, which is generally a verb.. What are the attributes of the array?

Attribute of the array: size of the array. Length

With this attribute, we can obtain the capacity value that can be stored by the array object, that is, the length of the array and the number of elements. This is a good understanding, and there are other attributes in the array, for example, the dimension of the array. The attribute usage is relatively simple. The other formats are basically the same. Here we will not give an example.

In the last example of the previous section, we used index to get the value of the array element.Array [Index],However, when the number of dimensions and capacity of an array is large, the indexing method is complicated.CodeA large amount of data can also reduce programming efficiency. To address this problem, C # provides the foreach Statement, which is used to read all elements in the Set/array. We call this function traversal. Syntax writing is as follows:

Traversal array: foreach (type objname in collection/array)

This statement checks the stored variable values in the array one by one and extracts them one by one. The type is the data type of the array object to be read in the objname variable, the objname defines a type variable name, which represents each element obtained from the collection and array (collection/array). Collection/array is the array object to be accessed. In this way, you only need to write a foreach to traverse the array of all dimensions except the staggered array.

Note: The data type of the objname must be the same or larger than the type of the collection/array object.

The following is an example of using foreach and for to traverse the rule array. It involves an array to obtain the dimension, and compares the advantages of foreach in one-time traversal rule array.

Int [,] A = new int [2, 2, 2] {1, 2}, {3, 4}, {5, 6 }, {7, 8 }}; // defines a two-row, two-column, two-depth, three-dimensional array.

For (INT I = 0; I <A. getlength (0); I ++) // use array. getlength (n) is used to obtain the number of dimension elements on the array [, N]. 0 represents vertical, 1 row, and N represents n + 1 dimension.

{

For (Int J = 0; j <A. getlength (1 );J ++)

{

For (INT z = 0; Z<A. getlength (2 );Z ++) // If the array has n dimensions, you have to write N for loops.

{

Console. writeline (A [I, j, Z]);

}

}

}

Use foreach loop to traverse array a at a time

Int [,] A = new int [2, 2, 2] {1, 2}, {3, 4}, {5, 6 }, {7, 8 }}; // defines a two-row, two-column, two-depth, three-dimensional array.
Foreach (int I in)
{
Console. writeline (I );
}

The execution results of these two types of code are the same. Each line has one element, eight rows in total, and the elements are 1 2 3 4 5 6 7 8 respectively.

The following example shows an example of using the for and foreach loops to access array elements. First, the user is prompted to enter the number of students, then, the number of students is used as the number of elements in the array names for storing the Student name. The "input Student name" prompt is displayed cyclically according to the index I of the array starting from 0 bits, the Student name entered by the user is stored in the names array according to its index method names [I]. The maximum number of for loop times (that is, the maximum index value) is passed through the array attribute. the length is obtained. In the previous lesson, we mentioned that the relationship between capacity and indexes is Index = array. length-1, which is the maximum value of I <names. length. After storage, the system prompts "output Student name". Then, the foreach loop is used to traverse each element stored in the names array (Student name) one by one and assign it to the name element one by one, and then output it to the console.

Through this example, we have reviewedC LanguageThe for loop learned in, the value of the array element is stored using indexes, and the usage of the. Length attribute and foreach traversal learned today, it must be noted that with the helpForeach can only retrieve elements in the array one by one. It cannot be used to change the elements stored in the array..The use of foreach and for is a programming skill that you must master. Students should pay attention.

Next let's learnStaggered ArrayIs an irregular two-dimensional array, which is the biggest difference from a rectangular array (two-dimensional array), because the length of each row in the array is not the same, we can think of itA two-dimensional array composed of one-dimensional arrays of different lengthsTherefore, the staggered array is also called the "array in the array", which saves memory space than the rectangular array of the specification. It also needs to be created and used according to its features. The syntax used to create an interleaved array is different from the preceding rectangular array. Two [] operators must be used. The first operator [N] represents the number of rows. Take a look at the following picture and use the picture examples to explain the declaration of the staggered array.

Staggered array declaration: rows are fixed
Step 1: int [] [] jaggedarray = new int [4] [];

If an array element is declared in the distributed manner, the number of elements must be written, because the rows of the staggered array are fixed, and the columns of each row are not fixed, therefore, the number of rows must be specified in the first [] during initialization.
Step 2: Initialize each line of the staggered Array
Jargedarray [0] = new int [6];
Jargedarray [1] = new int [2];
Jargedarray [2] = new int [3];
Jargedarray [3] = new int [5];

Show each row a one-dimensional array, define the number of columns, and then assign values to a single element using the Index Assignment Method. For example:

Step 3: Use the Index Assignment Method to assign values to a single element
Jargedarray [2] [0] = 5;
Jargedarray [3] [4] = 32;

Alternatively, you can merge the two or three steps above into one step and assign values to each row.
Step 2: Initialize and assign values to the staggered array directly
Jargedarray [0] = new int [] {1, 3, 5, 7, 9, 13 };
Jargedarray [1] = new int [] {0, 2 ,};
Jargedarray [2] = new int [] {5, 11, 22 };
Jargedarray [3] = new int [] {3, 5, 7, 10, 32 };

 

We can also initialize the array when declaring it, such:
Int [] [] jaggedarray = new int [] []
{

New int [] {1, 3, 5, 7, 9 },
New int [] {0, 2 },
New int [] {5, 11, 22 },
New int [] {3,5, 7,10, 32}
};

The following is an example of assigning values to the staggered array and traversing the staggered array. Let's see the code difference with the rule array. Let me explain the following example. I have defined three lines of staggered arrays. The first line outputs the name, mantra, and native place, the second row uses the direct value assignment method to define three columns: Liu Dafu, he is puzzled, and Disney. The third row only defines two columns, assign a value to the element of three rows and one column as the index. Then, assign a value to the element of two rows and one column as the wife!

String [] [] Xinxi = new string [3] [];
Console. writeline ("assigning a value to the staggered array! ");
Xinxi [0] = new string [] {"last name", "mantra", "nationality "};
Xinxi [1] = new string [] {"Liu Dafu", "very difficult", "One day, one hour"};
Xinxi [2] = new string [2];
Xinxi [2] [0] = "crayon shinect ";
Xinxi [2] [1] = "wife! ";
Console. writeline ("prepare output now! ");
Console. writeline ("*************");
Foreach (string [] Hang in Xinxi) // because of the feature of the staggered array, you must first use the array hang storage to traverse each row of the staggered array Xinxi.
{
Foreach (string lie in Hang) // traverses each column in the array of rows and stores it in the lie element.
{
Console. Write (lie); // output the traversal Element
}
Console. writeline ();
}

The result is displayed as follows:

 

 

 

 

 

Let's modify the above example to use the for loop output element, so that we can see the difference between the staggered array and the rule array.

Staggered array: String [] [] Xinxi = new string [3] [];
Console. writeline ("assigning a value to the staggered array! ");
Xinxi [0] = new string [] {"last name", "mantra", "nationality "};
Xinxi [1] = new string [] {"Liu Dafu", "very difficult", "One day, one hour"};
Xinxi [2] = New String [2];
Xinxi [2] [0] = "crayon shinect ";
Xinxi [2] [1] = "wife! ";
Console. writeline ("prepare output now! ");
Console. writeline ("******************************");
For (INT I = 0; I <Xinxi. length; I ++) // obtain the row index first.
{
For (Int J = 0; j <Xinxi [I]. length; j ++) // obtain the column index in the row.
{
If (Xinxi [I] [J]! = NULL) // if this element is not null, the output element value
{
Console. Write (Xinxi [I] [J]);
}
Else
{
Console. Write ("-------"); // if this element is null, output "-------"
}
}
Console. writeline ();
}

The output result is the same as that of the previous image. If the column element of the third row is defined as 3, the array is changed to a two-dimensional array of the three rows and three columns of the rule, or the element values with the index of 0 and 1:

Two-dimensional array:

String [] [] Xinxi = new string [3] [];
Console. writeline ("assigning a value to the two-dimensional array! ");
Xinxi [0] = new string [] {"last name", "mantra", "nationality "};
Xinxi [1] = new string [] {"Liu Dafu", "very difficult", "One day, one hour"};
Xinxi [2] = New String [3];
Xinxi [2] [0] = "crayon shinect ";
Xinxi [2] [1] = "wife! ";
Console. writeline ("prepare output now! ");
Console. writeline ("******************************");
For (INT I = 0; I <Xinxi. length; I ++) // obtain the row index first.
{
For (Int J = 0; j <Xinxi [I]. length; j ++) // obtain the column index in the row.
{
If (Xinxi [I] [J]! = NULL) // if this element is not null, the output element value
{
Console. Write (Xinxi [I] [J]);
}
Else
{
Console. Write ("-------"); // if this element is null, output "-------"
}
}
Console. writeline ();
}

The result is as follows:

 

 

Q: What are the differences between the two images?We didn't assign a value to the 3rd columns in the second row of a two-dimensional array, but ---- appears, indicating that it occupied the element at this position when it was created, only according to the principles described in the previous lesson, a default null value is given according to the data type. When we replace "------", the default null value can be displayed, instead of the staggered array, when no element is created, it does not exist.

In this section, we mainly learn how to traverse foreach in two arrays. In the next section, we will learn the common methods of arrays.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.