Arrays

Arrays

Structures that can store multiple data of the same type are called arrays. Arrays, like variables, cannot be used undeclared.

When defining arrays, we specify the type of elements, the number of elements, and the name of the array.

Array definition in C# is done like this:

DataType[ ] arrayName = new DataType[number of elements]

string[ ] days = new string[7];

In the above example, a string type array with 7 elements named gunler has been created.

int[ ] numbers = new int[24];

In this example, a 24-element array named numbers and integer is created.

Each element in the array has an index number, and the elements of the array can be accessed using this number. The point to note is that index numbers start from 0. Since the number of the first element of the array will be 0, the number of the last element will be 1 less than the total number of elements. The index number of the first element of the above 24-element array will be 0, while the number of the last element will be 23.

As with variables, the values ​​of array elements can be assigned at the definition stage. Since a large number of values ​​will be entered, different from the variable, these values ​​are written between curly brackets and with a comma between them.

string[ ] days = {"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday" };  

To reach any element of the array, the name of that array and the index number of the element are used. For example, element 3 of the array of days (Thursday)available as

days[ 3 ]

In this way, the value of the desired element can also be changed.

numbers[ 7 ] = 35;

Arrays and loops are often used together. Especially in arrays with a large number of elements, if all elements are to be processed, our work will be easier thanks to loops.

For example, let's use the for loop to print all the elements of the 20-element array named "myclass" into label1:

for( int i = 0 ; i <= 19 ; i++ )

{

Label1.Text = myclass[ i ] + “\n” ;

}

The foreach loop, a special loop for arrays, will be covered in the next topic.

 

Length property

Returns the length (number of elements) of the array.

int[ ] array1 = new int [11];

label1.text = array1.Length.toString();

In this example, 11 will be written in label1.

 

c# array examples, c# array definition, array tutorials, sorting array, array length, sort array, reverse array

EXERCISES

There are no examples related to this subject.



COMMENTS




Read 771 times.

Online Users: 3695



arrays-in-visual-c-sharp