In C#, an array is a data structure that stores a fixed and ordered collection of elements of the same type. Arrays are immutable and the size cannot be changed after initialization.
int[] myArray
In order to actually make the array, there are two options. Intialize the array with only the size or intialize the array with all components. If you choose the second option, the size is automatically detected. Here are both options
int[] myArray = new int[5]; // Creates an array of 5 integers
int[] myArray = { 1, 2, 3, 4, 5 }; // Initializes an array with values
In order to access any element of an array, we use different notation. Instead of using a period, we use brackets( [ ] ). Each element has an index associated and this is the position of it in the array. Unlike counting, this index starts at 0 NOT at 1. With this in mind, we can access elements.
myArray[0] // 0 is the INDEX and will return the FIRST element in the array
One important attribute that is used regulary when dealing with arrays is Length. This is not a method. Therefore when using it, we do not need (). Arrays can get confusing when dealing with indices and the length. The length is always one more than the last index. In myArray, the final index is 4. However, the length of the array is 5 because there are 5 total elements. Here is how to use Length.
myArray.Length
Data structures is where the knowledge of loops and conditionals really get tested. There are two main ways you can loop through arrays. For loop and for each loop. I mean...you can use a while loop but...don't.
For loop
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine($"Element at index {i}: {myArray[i]}");
}
For each loop. I never went through for each loops because it is only useful when learning about data structures and collections. Here is the basic structure of a for loop and how we can use it in this array example.
foreach (elementType variable in collection)
{
// Statements to be executed for each element
}
foreach (int num in myArray)
{
Console.WriteLine($"{num}");
}
As you can maybe see, with for each loops, you do not get access to the index the element has. Therefore, only use a for each loop when you know that the index is not necessary.