This is your first visit inside The Matrix. Welcome!

The Matrix has you…

This place will take you into the mirage of learning C# programming language, without any previous coding experience being required

Close
Sunday, June 24, 2018 08:53

## Arrays

We talked about arrays before, in an entire chapter. The arrays are collections of fixed number of elements of a given type (strings, integers, etc) where the elements preserve their initial order. Each element can be accessed through its numerical index, which starts at 0. The arrays are memory areas which have a predefined size. That’s why, adding a new element in an array is a slow operation. To do this, we first have to allocate a memory of the same size plus one, and copy all the data from the original array to the new one. Searching in an array takes time because we have to compare every element to the searched value. It takes N/2 comparisons in the average case. Removing an element from an array is also a slow operation. As before, we have to allocate a memory of the same size minus one, and copy all the old
elements except the removed one. Accessing elements by index is direct, and thus, a fast operation. The arrays should be used only when we have to process a fixed number of elements to which we need a quick access by index. For example, if we have to sort some numbers, we can keep them in an array and then apply some of the sorting algorithms. If we have to change the elements count, the array is not the correct data structure we should use. Use arrays when you have to process a fixed number of elements to which you need an access through index. An array is defined like this:

```[object type][] myArray = new [object type][number of elements]
```

Example:

```int[] myIntArray = new int[5];
int[] myIntArray2 = { 0, 1, 2, 3, 4 };
```

Arrays have a lot of methods, of which the following are the most useful:

```using System;
using System.Collections.ObjectModel;

class Program
{
static void Main()
{
int[] array = { 1, 5, 3 };

Console.WriteLine("Count: " + result.Count);
for (int i = 0; i < result.Count; i++)
{
// Can't touch this! (taaanana nana nana!)
Console.WriteLine(result[i]);
}
}
}
```

Array.BinarySearch() – This method quickly and accurately pinpoints the location of an element in the array. It can be told how to compare elements. It works correctly only on a presorted array. Example:

```using System;

class Program
{
static void Main()
{
// Source array that is ordered ascending.
string[] array = { "a", "e", "m", "n", "x", "z" };

// Call versions of the BinarySearch method.
int index1 = Array.BinarySearch(array, "m");
int index2 = Array.BinarySearch<string>(array, "x");
int index3 = Array.BinarySearch<string>(array, "E", StringComparer.OrdinalIgnoreCase);

// Write results.
Console.WriteLine(index1);
Console.WriteLine(index2);
Console.WriteLine(index3);
}
}
```

Array.Clear() – zeros out all elements. It provides a one-line, reliable and understandable way to empty or clear your array. It works on arrays of any type – including numbers, booleans, structs and class instances. Example:

```using System;

class Program
{
static void Main()
{
int[] integerArray = new int[] { 4, 6, 8, 1, 3 };

// Display the array
Console.WriteLine("--- Integer array before clear ---");
foreach (int value in integerArray)
{
Console.WriteLine(value);
}

// Clear all elements in the array.
Array.Clear(integerArray, 0, integerArray.Length);

// Display the array
Console.WriteLine("--- Integer array after clear ---");
foreach (int value in integerArray)
{
Console.WriteLine(value);
}
}
}
```

Array.ConvertAll() – allows you to declaratively convert an entire array with a single statement. It converts all elements in one array to another type. It incurs some performance overhead. But it can simplify code, particularly in programs where many different conversions take place. Example:

```using System;

class Program
{
static void Main()
{
// Integer array of 3 values.
int[] array1 = new int[3];
array1[0] = 4;
array1[1] = 5;
array1[2] = 6;

// Use ConvertAll to convert integer array to string array.
string[] array2 = Array.ConvertAll(array1, element => element.ToString());

// Write string array.
Console.WriteLine(string.Join(",", array2));
}
}
```

Array.Copy() – copies elements from one array to another. It has some complexities. This operation can result in certain exceptions. The type of elements – in both the target and source arrays – is important. This is a static method. Example:

```using System;

class Program
{
static void Main()
{
// Instantiate the source array.
int[] source = new int[5];
source[0] = 1;
source[1] = 2;
source[2] = 3;
source[3] = 4;
source[4] = 5;

// Instantiate and allocate the target array.
int[] target = new int[5];

// Copy the source to the target.
Array.Copy(source, target, 5);

// Display the target array.
Console.WriteLine("--- Target array ---");

foreach (int value in target)
{
Console.WriteLine(value);
}
}
}
```

Array.Exists() – provides a handy way to test for an element that matches a certain predicate condition. It involves some overhead and performance drawbacks. But it can be useful for certain programs. Example:

```using System;

class Program
{
static void Main()
{
string[] array = { "cat", "dot", "perls" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perls");
bool b = Array.Exists(array, element => element == "python");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

// Display bools.
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
}
}
```

Array.Find() – This method searches an array (with declarative syntax). We specify a Predicate type instance to determine what logic the search uses. Example:

```using System;

class Program
{
static void Main()
{
// Use this array of string references.
string[] array1 = { "cat", "dog", "carrot", "bird" };

// Find first element starting with substring.
string value1 = Array.Find(array1, element => element.StartsWith("car", StringComparison.Ordinal));

// Find first element of three characters length.
string value2 = Array.Find(array1, element => element.Length == 3);

// Find all elements not greater than four letters long.
string[] array2 = Array.FindAll(array1, element => element.Length <= 4);
Console.WriteLine(value1);
Console.WriteLine(value2);
string[] array2 = { "dot", "net", "perls" };

// Find last string of length 3.
string result = Array.FindLast(array2, s => s.Length == 3);
Console.WriteLine(result);

// Use this input array.
int[] array3 = { 5, 6, 7, 6 };

// Use FindIndex method with predicate.
int index1 = Array.FindIndex(array3, item => item == 6);
// Use LastFindIndex method with predicate.
int index2 = Array.FindLastIndex(array3, item => item == 6);

// Write results.
Console.WriteLine("{0} = {1}", index1, array3[index1]);
Console.WriteLine("{0} = {1}", index2, array3[index2]);
}
}
```

Array.ForEach() – loops over every element. It calls a method on each element in an array. It is a declarative syntax form. It simplifies certain code patterns. No loop construct is needed. Examples:

```using System;

class Program
{
static void Main()
{
int[] items = { 10, 100, 1000 };
// Display elements with ForEach.
Array.ForEach(items, element => Console.WriteLine("Element is " + element));
}
}
```

Array.IndexOf() – searches an array. It acts upon an array of any type. It locates the offset of the value specified. The IndexOf method on Array, in both its generic form and its LastIndexOf form, is useful in many program contexts. Example:

```using System;

class Program
{
static void Main()
{
// Example string array is declared.
string[] array = new string[6];
array[0] = null;
array[1] = "carrot";
array[2] = "rat";
array[3] = "";
array[4] = "carrot";
array[5] = "apple";

// Find string with this value starting at offset 2.
int index1 = Array.IndexOf(array, "carrot", 2, 3);

// Find a nonexistent string.
int index2 = Array.IndexOf(array, "banana");

// Write the result.
Console.WriteLine(index1);
Console.WriteLine(index2);
}
}
```

Array.LastIndexOf() – finds the last matching element. It searches from the end of an array. It returns the index of the element that contains the specified value. It has limitations – it may be of limited value. Examples:

```using System;

class Program
{
static void Main()
{
int[] array = { 2, 4, 6, 8, 6, 2 };

int result1 = Array.IndexOf(array, 6);
Console.WriteLine(result1);

int result2 = Array.LastIndexOf(array, 6);
Console.WriteLine(result2);

int result3 = Array.LastIndexOf(array, 100);
Console.WriteLine(result3);
}
}
```

Array.Resize() allocates a new array. It then copies existing element values to the new array. This logic is needed when an array’s size is inadequate. I show how Resize reallocates and copies elements:

```using System;

class Program
{
static void Main()
{
// Initialize array for example.
char[] array = new char[4];
array[0] = 'p';
array[1] = 'e';
array[2] = 'r';
array[3] = 'l';

// Display the array.
for (int i = 0; i < array.Length; i++)
Console.Write(array[i]);
Console.WriteLine();

// Resize the array from 4 to 2 elements.
Array.Resize(ref array, 2);

// Display the array that has been resized.
for (int i = 0; i < array.Length; i++)
Console.Write(array[i]);
Console.WriteLine();
}
}
```

Array.Reverse() – inverts the ordering of an array’s elements. This task could be accomplished with a for-loop. But the Array.Reverse() method is more convenient – and also easier to read. Example:

```using System;

class Program
{
static void Main()
{
// Input array.
int[] array = { 1, 2, 3 };

// Print.
foreach (int value in array)
Console.WriteLine(value);
Console.WriteLine();

// Reverse.
Array.Reverse(array);

// Print.
foreach (int value in array)
Console.WriteLine(value);
Console.WriteLine();

// Reverse again.
Array.Reverse(array);

// Print.
foreach (int value in array)
Console.WriteLine(value);
}
}
```

Array.Sort() – This method orders elements in an array. It modifies the array in-place. It handles different types of elements, including strings and ints. Example:

```using System;

class Program
{
static void Main()
{
// Simple sort call.
int[] values = { 4, 7, 2, 0 };
Array.Sort(values);
foreach (int value in values)
{
Console.Write(value);
Console.Write(' ');
}
Console.WriteLine();
}
}
```

Array.TrueForAll() – a static Array method. It gives you a declarative way to test every element in your array for some condition using a Predicate. It scans the array and returns true or false. Example:

```using System;

class Program
{
static void Main()
{
int[] values1 = { 1, 3, 5, 7 };
bool result1 = Array.TrueForAll(values1, y => y % 2 == 1);
Console.WriteLine(result1);

int[] values2 = { 2, 5, 8 };
bool result2 = Array.TrueForAll(values2, y => y % 2 == 1);
Console.WriteLine(result2);
}
}
```

The most important property of arrays is:

Length – an array has a length – this is its size (its element count). An int of 0 or greater is returned – no iteration is done (a cache is used). Example:

```using System;

class Program
{
static void Main()
{
// Basic array length example.
int[] arrayA = new int[5];
int lengthA = arrayA.Length;
Console.WriteLine(lengthA); // Writes 5

// Long array length example.
long longLength = arrayA.LongLength;
Console.WriteLine(longLength); // Writes 5

// Zero length array example.
int[] zero = new int[0];
int lengthZero = zero.Length;
Console.WriteLine(lengthZero); // Writes 0

// Null array length example exception.

// GetLength 0 example.
int lengthE = arrayA.GetLength(0);
Console.WriteLine(lengthE); // Writes 5

// GetLength 1 example exception.
// int lengthF = arrayA.GetLength(1);
// Console.WriteLine(lengthF);

// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10

// Two-dimensional Length example.
Console.WriteLine(two.Length); // Writes 50
}
}
```