Declaration and Allocation of Memory For Arrays: Arrays: What's An Array?

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Arrays:

What’s an Array?
Arrays are vital for most programming languages. They are collections of variables, which we call elements.

An array’s elements in C# are numbered with 0, 1, 2… N-1. Those numbers are called indices. The total number of
elements in a given array we call length of an array.

All elements of a given array are of the same type, no matter whether they are primitive or reference types. This
allows us to represent a group of similar elements as an ordered sequence and work on them as a whole.

Arrays can be in different dimensions, but the most used are the one-dimensional and the two-dimensional
arrays. One-dimensional arrays are also called vectors and two-dimensional are also known as matrices.

Declaration and Allocation of Memory for Arrays

In C# the arrays have fixed length, which is set at the time of their instantiation and determines the total number
of elements. Once the length of an array is set we cannot change it anymore.

Declaring an Array

We declare an array in C# in the following way:

int[] myArray;

In this example the variable myArray is the name of the array, which is of integer type (int[]). This means that
we declared an array of integer numbers. With [] we indicate, that the variable, which we are declaring, is an
array of elements, not a single element.

When we declare an array type variable, it is a reference, which does not have a value (it points to null). This is
because the memory for the elements is not allocated yet.

The figure below shows how a declared array variable looks, when the memory for elements of the array is not
allocated yet:
In the program’s execution stack the variable with the name myArray is created and its value is set to null
(meaning it holds no value).

Creation of an Array – the Operator "new"

In C# we create an array with the help of the keyword new, which is used to allocate memory:

int[] myArray = new int[6];

In this example we allocate an array with length of 6 elements of type int. This means that in the dynamic
memory (heap) an area of 6 integer numbers is allocated and they all are initialized with the value 0:

The figure shows, that after the allocation of memory for the array the variable myArray points to an address in
the dynamic memory, where the values are. In C#, the elements of an array are always stored in the dynamic
memory (called also heap).

During the allocation of the memory for an array we set the total number of the elements in the brackets (a non-
negative integer number), defining its length. The type of the elements is written after the reserved word new, so
we indicate what type of elements are going to be allocated in the memory.

Array Initialization and Default Values

Before we can use an element of a given array, it has to be initialized or to have a default value. In C# all variables,
including the elements of arrays have a default initial value. This value is either 0 for the numeral types or its
equivalent for the non-primitive types (for example null for a reference type and false for the bool type).

Of course we can set initial values explicitly. We can do this in different ways. Here is one of them:

int[] myArray = { 1, 2, 3, 4, 5, 6 };
In this case we create and initialize the elements of the array at the time of the declaration. On the figure below
we see how the array is allocated in the memory when its values are initialized at the moment of its declaration:

With this syntax we use curly brackets instead of the operator new. Between the brackets we list the initial values
of the array, separated by commas. Their count defines the length of the array.

Declaration and Initialization of an Array – Example


Here is one more example how to declare and initialize an array:

In this case we allocate an array of seven elements of type string. The type string is a reference type
(object) and its values are stored in the dynamic memory. The variable daysOfWeek is allocated in the stack
memory, and points to a section of the dynamic memory containing the elements of the array. The type of each of
these seven elements is string, which itself points to a different section of the dynamic memory, where the real
value is stored.

On this figure we see how the array is allocated in the memory:


Access to the Elements of an Array
We access the array elements directly using their indices. Each element can be accessed through the name of the
array and the element’s index (consecutive number) placed in the brackets. We can access given elements of the
array both for reading and for writing, which means we can treat elements as variables.

Here is an example for accessing an element of an array:

myArray[index] = 100;

In the example above we set a value of 100 to the element, which is at position index.

myArray[20] = 100;
In the example above we set a value of 100 to the element, which is at position index 20

Here is an example, where we allocate an array of numbers and then we change some of them:

int[] myArray = new int[6];


myArray[1] = 1;
myArray[5] = 5;
After the change, the array is allocated in the memory as shown below:

As we can see, all elements, except those for which values are explicitly set, are initialized with the value 0 when
the memory of the array was allocated.

Array using for loop:

We can iterate through the array using a loop statement. The most common form of such iteration is by using a
for-loop:
int[] arr = new int[5];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = i;
}

Reversing an Array – Example (I didn’t understand how it works)


class ArrayReverseExample
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5 };
// Get array size
int length = array.Length;
// Declare and create the reversed array
int[] reversed = new int[length];
// Initialize the reversed array
for (int index = 0; index < length; index++)
{
reversed[length - index - 1] = array[index];
}

// Print the reversed array


for (int index = 0; index < length; index++)
{
Console.Write(reversed[index] + " ");
}
}
}
// Output: 5 4 3 2 1

Reading an Array from the Console


int n = int.Parse(Console.ReadLine());
int[] array = new int[n];
for (int i = 0; i < n; i++)
{
array[i] = int.Parse(Console.ReadLine());
}
Initially we read a line from the console using Console.ReadLine(), and then we parse that line to an integer
number using int.Parse() and we set it to the variable n. We then use the number n as length of the array.

Again we use a loop to iterate through the array. At each iteration we set the current element to what we have
read from the console. The loop will continue n times, which means it will iterate through the array and so we will
read a value for each element of the array:

Printing an Array to the Console


string[] array = { "one", "two", "three", "four" };
for (int index = 0; index < array.Length; index++)
{
// Print each element on a separate line
Console.WriteLine("Element[{0}] = {1}", index, array[index]);
}
We are iterating through the array using the for-loop, which will go array.Length times, and we will print
the current element using Console.WriteLine() and a formatted string. Here is the result:

Element[0] = one
Element[1] = two
Element[2] = three
Element[3] = four
Iteration through Elements of an Array
As we can see, the iteration through the elements of an array is one of the most used techniques when we work
with arrays. Consecutive iterating using a loop will allow us to access each element through its index and we will
be able to modify it as we want. We can do that with different loop constructs, but the most appropriate loop is
the for-statement. We will examine in details how this type of iteration works.

Iteration with a For Loop


It is a good practice to use for-loops, when we work with arrays and structures with indices. In the following
example we will double the values of all elements of an array of numbers and we will print them:

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


Console.Write("Output: ");
for (int index = 0; index < array.Length; index++)
{
// Doubling the number
array[index] = 2 * array[index];
// Print the number
Console.Write(array[index] + " ");
}
// Output: 2 4 6 8 10

You might also like