JavaScript Error

You currently have JavaScript disabled on your web browser.

This website uses JavaScript, and This web page needs JavaScript activated to work correctly.

Please active JavaScript on your web browser and then refresh this web page.



Arrays



An array is a data structure collection object that contains multiple variables. The variables contained in an array are called elements of the array, and are accessed by their computed indexed indices. C# arrays are indexed using the zero index approach, meaning that the first element in the array has an index value of 0, the second element has an index value of 1, the third element has an index value of 2, and so on and so forth, and incrementing sequentially until the end of the array.

All of the elements of an array must be of the same variable type. For example, if you have an array of int variables then every element of that array must be on an integer data type. If you have an array of string variables then every element of that array must be of a string data type.

Note: If you want or need to have a data structure collection object which contains various different data types, so that one element is an int and one element is a string (for example), then use a List object instead of an Array object.

Creating Arrays

To create an array, define the variable type using square brackets:

 
string[] animals;

The above example declared a variable named "animals" that holds an array of strings.

There are various ways to assign values to an array. One way to insert values to the array, is to use the array literal by placing the values in a comma-separated list, inside curly braces, and assigning it to the variable during declaration:

 
string[] animals = {"cat", "dog", "bird", "fish"};

Another example, we could create an array of integers as follows:

 
int[] myIntArray = {3, 8, 12, 44, 7, -19, 533, 0, -28, 8, 8, 8, 52};

It is often more useful to create an array of empty values, and then assign values to the arrays elements later:

 
int[] myIntArray = new int[13];

myIntArray[0] = 3;
myIntArray[1] = 8;
myIntArray[2] = 12;
myIntArray[3] = 44;
myIntArray[4] = 7;
myIntArray[5] = -19;
myIntArray[6] = 533;
myIntArray[7] = 0;
myIntArray[8] = 28;
myIntArray[9] = 8;
myIntArray[10] = 8;
myIntArray[11] = 8;
myIntArray[12] = 52;

The above example creates an integer array that has 13 empty elements of integer variable type. It then assigns the values of each element by accessing that element using its index value and then assigning an integer value to it.

Note: The first element within all C# arrays will always have an index value of zero (0), and increment sequentially accordingly.

Accessing the Elements of an Array

You can access the value stored within an array element by referring to the index number of that element. Once you access that element, you can either read that elements variable value and/or assign a new value to that elements variable (as long as you do not try and change the variable type of that element):

 
// create an int array and assign values to it
int[] myIntArray = {3, 8, 12, 44, 7, -19, 533, 0, -28, 8, 8, 8, 52};

// read the 6th element of the array and output its value to the console
Console.WriteLine(myIntArray[5]);   // outputs -19

// assign a new value to the 6th element of the array
myIntArray[5] = 7;

// read the 6th element of the array and output its value to the console
Console.WriteLine(myIntArray[5]);   // outputs 7


Array Length

To find out how many elements an array has, use the Length property:

 
// create a string array and assign values to its elements
string[] animals = {"cat", "dog", "bird", "fish"};

// create an integer variable and assign the Length of the animals array to it
int tempLength = animals.Length;

// output the length value to the console window
Console.WriteLine(tempLength);   // outputs 4


Loop Through An Array

There may be times when your program needs to loop through the elements of an array. There are various ways to loop through an array, and you are able to loop from any element index to any other element index within that array, or you can loop from the first element of that array to its last element.

Note: Take notice that the first element within all C# arrays will always have an index value of zero (0), and each elements index value will increment sequentially accordingly until the end of the array is reached.
Note: Take care not to attempt to access an index value for an element that does not exist within that array, as doing so may result in an error at best or may corrupt the values stored in other variables at worst.

The following is an example of looping through an array using the for method, and loops from the first element of the array to the last element of the array:

 
// create a string array and assign values to its elements
string[] animals = {"cat", "dog", "bird", "fish"};

// create an integer variable and assign the Length of the animals array to it
int tempLength = animals.Length;

// loop through each element of the array from index 0 (which is the first element of the array) to the last element of the array
for(int i=0; i<tempLength; i++)
{
	// output the element value to the console window
	Console.WriteLine(animals[i]);
}

With the for method, it is possible to loop just a portion of the array instead of the entire array by specifying which index values to loop through:

 
// create a string array and assign values to its elements
string[] animals = {"cat", "dog", "bird", "fish"};

// create an integer variable and assign the Length of the animals array to it
int tempLength = animals.Length;

// loop through each element of the array from index 2 (which is the 3rd element of the array) to the last element of the array
for(int i=2; i<tempLength; i++)
{
	// output the element value to the console window
	Console.WriteLine(animals[i]);
}

Alternatively, the foreach loop method could also have been used, and is best used whenever your program does not need to know the Length of the array, and when your program will always loop from the first element to the last element of the array:

 
// create a string array and assign values to its elements
string[] animals = {"cat", "dog", "bird", "fish"};

// loop through each element of the array
foreach(string thisAnimal in animals)
{
	// output the element value to the console window
	Console.WriteLine(thisAnimal);
}

Sorting An Array

The Array class offers many useful methods, including the Sort() method. The Sort() method sorts an array alphabetically or numerically, in an ascending order:

 
// create a string array and assign values to its elements
string[] animals = {"cat", "dog", "bird", "fish"};

// sort the animal array so that it is in ascending alphabetical order
Array.Sort(animals);

// loop through each element of the sorted array
foreach(string thisAnimal in animals)
{
	// output the element value to the console window
	Console.WriteLine(thisAnimal);
}

 
// create an int array and assign values to it
int[] myIntArray = {3, 8, 12, 44, 7, -19, 533, 0, -28, 8, 8, 8, 52};

// sort the integer array so that it is in ascending numerical order
Array.Sort(myIntArray);

// loop through each element of the sorted array
foreach(string thisValue in myIntArray)
{
	// output the element value to the console window
	Console.WriteLine(thisValue);
}

Multidimensional Arrays

The array examples listed above are known as Single Dimension Arrays, or a 1-D array. If you were to view the data of the 1-D array in a tabular form (such as in a data grid or Excel spreadsheet), then it would look like a single column of data that has multiple rows. In this 1-D array, each row represents a single element, and the array of elements is the single column of rows.

Multi Dimension Arrays are arrays of arrays. One way to mentally visualize them is as follows: a 2-D array would look like a single spreadsheet that has multiple columns, where each column has the same number of rows, and the element would be the cell located at X (column) and Y (row). A 3-D array would look like a stack of multiple spreadsheets contained within one workbook, where each spreadsheet has multiple columns and rows of cells. A 4-D array would look like a stack of multiple workbooks where each workbook contains multiple spreadsheets that have multiple columns and rows of cells in each. A 5-D array would look like a shelf which contains multiple workbooks sitting on it. A 6-D array would look like a book shelf that has multiple shelves of workbooks. A 7-D array would look like a room that has multiple book shelves. A 8-D array would look like a building that has multiple rooms filled with multiple bookshelves in each. A 9-D array would look like a city that has multiple buildings. A 10-D array would look like a state that has multiple cities. A 11-D array would look like a continent that has multiple states. A 12-D array would look like a planet with multiple continents. A 13-D array would look like a solar system with multiple planets. A 14-D array would look like a galaxy with multiple solar systems in it. A 15-D array would look like a section of the universe that has multiple galaxies in it. And so on, and so forth. Figuratively speaking, of course. In reality, they are nothing more than arrays within arrays of variables.

Although it is possible to create as many dimensions as you want, it is not practice, because your computer would very quickly run out of memory. This is because each element is a variable of a data type. Variables of data types have and use a fixed amount of memory (2 bytes, 4 bytes, 16 bytes, 32 bytes, 64 bytes, etc.. per variable : per array element). A single dimension array is a collection of elements, and a multi dimension array is a collection of arrays. Therefore, the larger the collection is, the more memory all of those elements collectively require and consume, regardless of if you assign a value to them or not.

A 2-D array (or 2D array, however you prefer to describe it) is the most commonly used multi-dimensional array. The best way to visualize 2-D arrays is to think of an Excel spreadsheet. The array contains an X and Y index value, which points to the element (i.e. to the spreadsheets cell).

To create a 2-D array, instantiate an instance of the data type using a [,] instead of a []. Then assign the values by to each dimension of the array within its own set of curly braces, separated by a comma (,):

 
int[,] myIntArray = { {1,2,3}, {4,5,6} };

The above example creates a 2-D integer array that contains 2 rows, where each row has 3 columns.

The single comma [,] specifies that the array is two-dimensional. A three-dimensional array would have two commas : [,,]. A four-dimensional array would have three commas : [,,,], and so on and so forth.

Very rarely will you ever see or work with arrays larger than three-dimensions.


Accessing Elements Of Multidimensional Arrays

To access an element of a two-dimensional array, you must specified two indexes : one for the Y (the row) and one for the X (the column).

The following example demonstrates accessing the value of the element in the first row (0) and third column (2):

 
int[,] myIntArray = { {1,2,3}, {4,5,6} };
Console.WriteLine(myIntArray[0, 2]);   // outputs 3

To loop through multi-dimensional arrays, call the .GetLength(n) method of the array, where n is the dimension index that you want to get the length of:

 
int[,] myIntArray = { {1,2,3}, {4,5,6} };
int yLength = myIntArray.GetLength(0);
int xLength = myIntArray.GetLength(1);

for (int y = 0; y < yLength; y++)
{
  for (int x = 0; x < xLength; x++)
  {
    Console.WriteLine(myIntArray[y, x]);
  }
}


Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


(0) pollYesResult
(0) pollNoResult



 
     About   |   Contact Us   |   Privacy   |   Terms & Conditions   |   © 2024 - T&J Divisions, LLC, All Rights Reserved