[C#] C# Arrays

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in the class “Programming 1 - COMP 100-002”


C# Arrays

What is Arrays?

  • Multi-value variable
  • A set of values that shares the same name
    • Midterm marks of all the students in COMP100
  • Each value is called an item or element
    • The elements are referenced by using a subscript
    • Subscripts are integer and starts at 0
  • Used extensively in legacy code
  • The size of Array can change, but it is a potentially expensive operation


Why Arrays?

  • One identifier for the array
    • Add readability to your code
    • Identifier for lots of variables
    • Easy to process the all the values → First index starts at 0 and goes to one less than the size
  • The items are stored sequentially in memory
    • Very efficient in storage and accessing items
  • Problems:
    • All the items must be on the same type


Create an Array

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

  1. To declare an array, define the variable type with square brackets:

    string[] cars;
    
  2. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:

    string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    
  3. To create an array of integers, you could write:

    int[] myNum = {10, 20, 30, 40};
    
  Other Variable Array Variable
Declaration int mark; int[] marks;
Allocating Storage   marks = new int[38];
Setting a Value mark = 78; marks[0] = 78;


Initializing an Array

int[] age = new int[34];

string[] colors = {"red", "green", "blue"};

char[] resistors = "roygbiv".ToCharArray();

string[] pm = "Justin Elliot Trudeau".Split();


Access the Elements of an Array

You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
// Output: Volvo

Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Setting Values

marks[0] = 75; //assigns 75 to the first item
marks[1] = 91; //assigns 91 to the second item
vowels[0] = 'a';
vowels[1] = 'e';
vowels[2] = 'i';
vowels[3] = 'o';
vowels[4] = 'u';

Getting Values

Console.WriteLine(marks[0]); //Output: the first item '75'
Console.WriteLine(marks); //Gibberish(헛소리)


Shortcuts

Declaration & Allocation & Initialization

//declares a char array that contains the chars a,e,i,o,u
char[] vowels = {'a', 'e', 'i', 'o', 'u'};

//declares a int array that contains the integers 2, 3, 5, 7, 11, 17, 19
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19};

//declares a string array that containing the first line of the famous nursery rhyme
string[] poem = {"Mary", "had", "a", "little", "lamb"};

//declares a string to hold the names of the president
string[] obama = {"Barak", "Hussein", "Obama"};


Change an Array Element

To change the value of a specific element, refer to the index number:

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
// Output: Opel (instead of Volvo)


Array Length

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

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);
// Output: 4
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
Console.WriteLine(vowels.Length);

int[] primes = {2, 3, 5, 7, 11, 13, 17, 19};
Console.WriteLine(primes.Length);

string[] poem = {"Mary", "had", "a", "little", "lamb"};
Console.WriteLine(poem.Length);

string[] obama = {"Barak", "Hussein", "Obama"};
Console.WriteLine(obama.Length);


Other Ways to Create an Array

If you are familiar with C#, you might have seen arrays created with the “new” keyword, and perhaps you have seen arrays with a specified size as well. In C#, there are different ways to create an array:

// Create an array of four elements, and add values later
string[] cars = new string[4];

// Create an array of four elements and add values right away
string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"};

// Create an array of four elements without specifying the size
string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"};

// Create an array of four elements, omitting the new keyword, and without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

It is up to you which option you choose. In our tutorial, we will often use the last option, as it is faster and easier to read.

However, you should note that if you declare an array and initialize it later, you have to use the new keyword:

// Declare an array
string[] cars;

// Add values, using new
cars = new string[] {"Volvo", "BMW", "Ford"};

// Add values without using new (this will cause an error)
cars = {"Volvo", "BMW", "Ford"};


C# Loop Through Arrays

Loop Through an Array

You can loop through the array elements with the “for” loop, and use the “Length” property to specify how many times the loop should run.

The following example outputs all elements in the cars array:

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.Length; i++)
{
  Console.WriteLine(cars[i]);
}
/* Output:
Volvo
BMW
Ford
Mazda */


Display all the items in an array

string[] poem = {"Mary", "had", "a", "little", "lamb"};
Console.WriteLine(poem);//will print gibberish

int counter = 0;
do
{
  Console.WriteLine(poem[counter]);
  counter++;
} while (counter < poem.Length);


Updating all the items in an array

double[] marks = {50, 67, 73, 55, 89, 68, 66, 76, 49};
int counter = 0;

while (counter < marks.Length){
  marks[counter] += 3;
  counter++;
}

//now we can print the updated array
counter = 0;

while (counter < marks.Length){
  Console.WriteLine(marks[counter]);
  counter++;
}


Summing all the items in an array

int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 37, 41, 47};

int sum = 0;
for (int counter = 0; counter < primes.Length; counter++)
{
  sum += primes[counter];
}

//now we can display the sum
Console.WriteLine($"the sum is {sum}");


Built-in Methods to return arrays

The Split() method of the object string explodes the individual words to produce a string array.

string[] poem = "Mary had a little lamb".Split();
string[] obama = "Barak Hussein Obama".Split();
string[] sillyWords = "foo bar baz quux".Split();

The ToCharArray() method of the object string “explodes” the individual letter to produce a char array.

char[] vowels = "aeiou".ToCharArray();
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
char[] letters = "Narendra".ToCharArray();


The foreach Loop

There is also a “foreach” loop, which is used exclusively to loop through elements in an array:

Syntax

foreach (type variableName in arrayName)
{
  // code block to be executed
}

The following example outputs all elements in the cars array, using a foreach loop:

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

foreach (string i in cars)
{
  Console.WriteLine(i);
}
/* Output:
Volvo
BMW
Ford
Mazda */

The example above can be read like this: for each string element (called i - as in index) in cars, print out the value of i.

If you compare the for loop and foreach loop, you will see that the foreach method is easier to write, it does not require a counter (using the Length property), and it is more readable.

int[] numbers = {3, 2, 6, 8, 1, 9, 5, 7, 4, 0};

foreach(int x in numbers)
{
  //x assumes the value of each item of the array
  //starting with the first and ending with the last

  //the variable x is read only!!!
  Console.WriteLine(x);
}


C# Methods of the Arrays Class

  • Array.Reverse()
    Reverses the order of the items in the array. i.e. the first becomes the last and the second becomes the second from the end
  • Array.Sort()
    Arranges the item from smallest to the largest or in ascending alphabetic order for strings
  • Array.BinarySearch()
    Returns the index of the item in a sorted array, or a negative value if there are no occurrence of the item in the array


Array.Reverse()

int[] numbers = {3, 2, 6, 8, 1, 9, 5, 7, 4, 0};
//3, 2, 6, 8, 1, 9, 5, 7, 4, 0

Array.Reverse(numbers);
//The array numbers will now look like: 0, 4, 7, 5, 9, 1, 8, 6, 2, 3


Array.Sort()

int[] numbers = {3, 2, 6, 8, 1, 9, 5, 7, 4, 0};
//3, 2, 6, 8, 1, 9, 5, 7, 4, 0

Array.Sort(numbers);
The array numbers will now look like: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

There are many array methods available, for example “Sort()”, which sorts an array alphabetically or in an ascending order:

// Sort a string
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
foreach (string i in cars)
{
  Console.WriteLine(i);
}
/* Output:
BMW
Ford
Mazda
Volvo */
// Sort an int
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{
  Console.WriteLine(i);
}
/* Output:
1
5
8
9 */


Array.BinarySearch()

int[] numbers = {3, 2, 6, 8, 1, 9, 2, 3, 4, 0};
//3, 2, 6, 8, 1, 9, 2, 3, 4, 0

Array.Sort(numbers);
The array numbers will now look like: 0, 1, 2, 2, 3, 3, 4, 6, 8, 9

Array.BinarySearch(numbers, 4); // => 6
Array.BinarySearch(numbers, 2); // => 2 or 3
Array.BinarySearch(numbers, 5); // => a negative value


System.Linq Namespace

Other useful array methods, such as “Min”, “Max”, and “Sum”, can be found in the “System.Linq” namespace:

using System;
using System.Linq;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] myNumbers = {5, 1, 8, 9};
      Console.WriteLine(myNumbers.Max());  // returns the largest value
      Console.WriteLine(myNumbers.Min());  // returns the smallest value
      Console.WriteLine(myNumbers.Sum());  // returns the sum of elements
    }
  }
}
/* Output:
9
1
23 */


C# Multidimensional Arrays

Using an array to capture attendance!

int[] mon = {1, 1, 0, 1, 1, 1, 0, 1, 1, 1}
// 1 1 0 1 1 1 0 1 1 1

int[] tue = {1, 1, 0, 0, 1, 1, 1, 1, 1, 1}
// 1 1 0 0 1 1 1 1 1 1

int[,] wk10 = {
                {1, 1, 0, 1, 1, 1, 0, 1, 1, 1},
                {1, 1, 0, 0, 1, 1, 1, 1, 1, 1}};
// 1 1 0 1 1 1 0 1 1 1
// 1 1 0 0 1 1 1 1 1 1


Multidimensional Arrays

In the previous chapter, you learned about arrays, which is also known as single dimension arrays. These are great, and something you will use a lot while programming in C#. However, if you want to store data as a tabular form, like a table with rows and columns, you need to get familiar with multidimensional arrays.

A multidimensional array is basically an array of arrays.

Arrays can have any number of dimensions. The most common are two-dimensional arrays (2D).


2-Dimensional Arrays

To create a 2D array, add each array within its own set of curly braces, and insert a comma (,) inside the square brackets:

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

The single comma [,] specifies that the array is two-dimensional. A three-dimensional array would have two commas: int[,,].

“numbers” is now an array with two arrays as its elements. The first array element contains three elements: 1, 4 and 2, while the second array element contains 3, 6 and 8. To visualize it, think of the array as a table with rows and columns:

  Column 0 Column 1 Column 2
Row 0 1 4 2
Row 1 3 6 8


Access Elements of a 2D Array

To access an element of a two-dimensional array, you must specify two indexes: one for the array, and one for the element inside that array. Or better yet, with the table visualization in mind; one for the row and one for the column (see example below).

This statement accesses the value of the element in the first row (0) and third column (2) of the “numbers” array:

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Console.WriteLine(numbers[0, 2]);
// Output: 2


Change Elements of a 2D Array

You can also change the value of an element.

The following example will change the value of the element in the first row (0) and first column (0):

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
numbers[0, 0] = 5;  // Change value to 5
Console.WriteLine(numbers[0, 0]);
// Output: 5 instead of 1


Loop Through a 2D Array

You can easily loop through the elements of a two-dimensional array with a foreach loop:

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

foreach (int i in numbers)
{
  Console.WriteLine(i);
}
/* Output:
1
4
2
3
6
8 */

You can also use a for loop. For multidimensional arrays, you need one loop for each of the array’s dimensions.

Also note that we have to use “GetLength()” instead of “Length” to specify how many times the loop should run:

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

for (int i = 0; i < numbers.GetLength(0); i++)
{
  for (int j = 0; j < numbers.GetLength(1); j++)
  {
    Console.WriteLine(numbers[i, j]);
  }
}
/* Output:
1
4
2
3
6
8 */


3-Dimensional Arrays

The items are accessed via three indices

int[, ,] arr3d1 = new int[1, 2, 2]{
                { { 1, 2}, { 3, 4} }
            };

int[, ,] arr3d2 = new int[2, 2, 2]{
                { {1, 2}, {3, 4} },
                { {5, 6}, {7, 8} }
            };

int[, ,] arr3d3 = new int[2, 2, 3]{
                { { 1, 2, 3}, {4, 5, 6} },
                { { 7, 8, 9}, {10, 11, 12} }
            };

arr3d2[0, 0, 0]; // returns 1
arr3d2[0, 0, 1]; // returns 2
arr3d2[0, 1, 0]; // returns 3
arr3d2[0, 1, 1]; // returns 4
arr3d2[1, 0, 0]; // returns 5
arr3d2[1, 0, 1]; // returns 6
arr3d2[1, 1, 0]; // returns 7
arr3d2[1, 1, 1]; // returns 8




Back to Top

See other articles in Category CS

Leave a comment