To declare an array you must first have the data type followed immediately by empty square brackets. After that you put the array's name. Here is how to declare an array of integers called arr.
int[] arr;
This is not an array yet but just a reference to an array. You must set the number of dimensions using the new keyword followed by the data type again with square brackets after it that contain the number of elements you want in the array. The following example creates an array with 3 elements.
int[] arr = new int[3];
The following table will help you imagine what an array looks like.
Element Number | Value |
---|---|
0 | 5 |
1 | 12 |
2 | 7 |
arr[0] = 5;
arr[1] = 12;
arr[2] = 7;
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
Console.WriteLine(arr[2]);
Arrays with loops
It is much easier to work with an array when you use a loop. Here is an example of how to print all the values in an array of 10 elements using a for loop.
int[] arr = new int[10];
for (int x = 0; x < 10; x++)
Console.WriteLine(arr[x]);
You can go through all the elements in an array without having to specify how many of them there are by using a foreach loop. In the following example the y is given the value of each element of the array for each iteration of the loop.
foreach (int y in arr)
Console.WriteLine(y);
Multi-dimensional arrays
A multi-dimensional array is an array that has elements in more than one dimension. A 2-dimensional can be thought of as having both an x and a y dimension. You do get arrays with more than 2 dimensions but they are not used very often. Here is a table that will help you imagine what a 2-dimensional array looks like.0 | 1 | 2 | |
---|---|---|---|
0 | 1 | 2 | 3 |
1 | 4 | 5 | 6 |
2 | 7 | 8 | 9 |
int[,] arr2 = new int[3,3];
You also use a comma when setting the value.
arr2[1,2] = 5;
2 loops are needed when working with a 2-dimensional array. The one loop must be put inside the other. Here is an example of how to print all the values of a 2-dimensional array.
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
Console.WriteLine(arr2[i,j]);
1 comments:
Nice post very helpful
dbakings
Post a Comment