Arrays

Intro

Task: Store the names of all tutorium atendees (For demonstration purpose we consider only Alf, Bert and Carl).

Bad solution:

string name01 = "alf";
string name02 = "bert";
string name03 = "carl";

Not very efficient, hard to manage, takes much time.

Better solution: Arrays

We can identify arrays by the square brackets []

We saved single values by using variables, arrays use the same datatypes and are also considered a variable, but a variable containing multiple values:

Please make sure you are aware what Declaration and Initialization means.

Declaration

Declaration of a single value variable

int number;

Declaration of an array variable

Declaration of an array looks nearly the same, we just add the square brackets to the datatype:

string[] names;

Initialization

Declaring and initializing a single value variable

int number = 5;

The first thing you should consider about arrays, is that we need to specify the size (amount of values stored) before we can use it. This size is not changeable afterwards, even if there are methods which simulate this behaviour.

Declaring and initializing an array:

string[] names = new string[3]; // Empty array that stores 3 values

Storing Values

For accessing multiple values in the same variable we use an so called index. A numeric value starting by zero.

names[0] = "alf";
names[1] = "bert";
names[2] = "carl";

Reading Values

For reading we also use the index:

Console.WriteLine(names[0]);
Console.WriteLine(names[1]);
Console.WriteLine(names[2]);

Output:

alf
bert
carl

Datatypes

We can use any datatype we want:

string[] array01;   // Array of strings 
int[] array02;      // Array of integers
double[] array03;   // Array of doubles
bool[] array04;     // Array of booleans
char[] array05;     // Array of chars
object[] array06;   // Array of objects

Different Ways of Initialization

We already initialized an empty array:
string[] names = new string[3]; // Empty array that stores 3 values
But we also can initialize an array directly with values using curly braces {}:
string[] names = new string[3] { "alf", "bert", "carl" }; // Array that stores 3 values
We can specify the size, but that is optional, because the information is redundant:
string[] names = new string[] { "alf", "bert", "carl" }; // Array that stores 3 values

Works exactly the same.

Be aware that the size-parameter and the number of values have to be the same if specified.
string[] names = new string[3] { "alf", "bert"}; // Error

Error CS0847 An array initializer of length '3' is expected

There is also a simplified syntax for initializing an array directly with values:

string[] names01 = new string[3]; // Empty array that stores 3 values
string[] names02 = new string[3] { "alf", "bert", "carl" }; // Array that stores 3 values
string[] names03 = new string[] { "alf", "bert", "carl" }; // Array that stores 3 values
string[] names04 = { "alf", "bert", "carl" }; // Simplified Syntax

The simplified syntax only works when declaring an array in the same instruction.

Example of wrong syntax:
string[] names; // This is ok
names = { "alf", "bert", "carl" }; // This is NOT ok - Error

Error CS1525 Invalid expression term '{'

In this case do not use the simplified syntax:
string[] names;
names = new string[] { "alf", "bert", "carl" }; // No Error

via GIPHY

Multidimensional Jagged Arrays

The previous example is a one dimensional array: for every value we need exatly one index for access.

Multidimensional Arrays have multiple dimensions, what makes the syntax hard to read. Clean code formating is a must here.

Let us use the name-list from before and think of multiple courses.
Therefore we want to store multiple arrays. An array containing arrays is called a jagged array.
The syntax is as folows:

string[][] courses = new string[3][];
courses[0] = new[] { "alf", "bert", "carl" };
courses[1] = new[] { "don", "ed" };
courses[2] = new[] { "fred", "grog", "hok", "irr", "jax" };

So we created an array containing three arrays, let us visualize that:

Can we store an array of a different type into a jagged array?

No we can't do that. But with some advanced stuff we can work around that later..

Multidimensional Non-Jagged Arrays

There are also multidimensional arrays, that do not contain of multiple arrays:
string[,] courses = new string[3,5];
courses[0, 0] = "alf";
courses[0, 1] = "bert";
// and so on..

We can also store the values when declaring the array, but we have to use the right amount of values:

string[,] courses = new string[3, 5] {
    { "alf", "bert", "carl", "-", "-" },
    { "don", "ed", "-","-","-" },
    { "fred", "grog", "hok", "irr", "jax" }
};

Let us visualize that again:

Three Dimension Non-Jagged Array

Here is an example:
string[,,] tutoriums = new string[2, 3, 5] {
    { 
        { "alf", "bert", "carl", "-", "-" }, 
        { "don", "ed", "", "", "" }, 
        { "fred", "grog", "hok", "irr", "jax" }
    },
    { 
        { "etc", "etc", "", "", "" }, 
        { "", "", "", "", "" }, 
        { "", "", "", "", "" }
    }
};

Line 1: Notice the two commas in both of the square brackets [,,] and [2, 3, 5]. This is difference to jagged arrays.
Clean formating is a must.

Reading a three dimensional array:
for (int i1 = 0; i1 < tutoriums.GetLength(0); i1++) {
    for (int i2 = 0; i2 < tutoriums.GetLength(1); i2++) {
        for (int i3 = 0; i3 < tutoriums.GetLength(2); i3++) {
            Console.Write(tutoriums[i1, i2, i3] + "_-_");
        }
        Console.WriteLine();
    }
    Console.WriteLine();
}

Ouput:

alf_ - _bert_ - _carl_ - _ - _ - _ - _ - _
don_ - _ed_ - __ - __ - __ - _
fred_ - _grog_ - _hok_ - _irr_ - _jax_ - _

etc_ - _etc_ - __ - __ - __ - _
_ - __ - __ - __ - __ - _
_ - __ - __ - __ - __ - _

Exercise

  1. Copy this code, run it, read it and test it pls.
  2. Calculate the average value of all numbers stored in the array and print the number on the screen.
// Declaration
string userinput;
int arraysize;            
int[] numbers; // Declaration of an integer array called numbers
// Get array size from user
Console.Write("Please enter size: ");
userinput = Console.ReadLine();
arraysize = Convert.ToInt32(userinput);
// Initalize array            
numbers = new int[arraysize];
// Get numbers from user
for (int i = 0; i < numbers.Length; i++) {
    Console.Write("Please enter number: ");
    userinput = Console.ReadLine();
    numbers[i] = Convert.ToInt32(userinput);
}
// Print array
Console.Write("Array Output: ");
for (int i = 0; i < numbers.Length; i++) {
    Console.Write(numbers[i] + " ");
}
// Print average value
/* Please add your code here*/
Example:
Please enter size: 4
Please enter number: 12
Please enter number: 32
Please enter number: 5
Please enter number: 48
Array Output: 12 32 5 48
Average value: 24,25