 ×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

# Arrays in C#

See in this article a general approach about arrays, understanding since its definition till practical application examples in C#.

"Arrays can be defined as series, collections or lists of elements generally of the same type of data, stored in a sequencial way". As this definition, the array is one of the most simple data structure, such in terms of its theoretical functioning understanding, as at the implementation level. However, this considerable simplicity do not reduce its importance on computing, because in so many situations, arrays are the most practical solution of problems in the "computing world".

When dealing with object lists (calling "objects" the elements of the array, not only one instance of classes, as also the mainly types-value) of a determines type-value of data, the use of arrays can be the best alternative, once the access to the elements is considerably fast, because the values are stored directly in the stack. The way this structure is treated in the memory is below commented.

### Arrays, matrices and other N dimensions

Arrays can be simple and sequential, like also composed collections, it means, they can possess such as one but many dimensions. An array of one dimension is called just an ARRAY, but one with many dimensions is called a MATRIX. This definition is similar to the one studied on algebra, and as such, we could only visualize down to three-dimension arrays.

In the arrays, each element is identified by a unique index that indicates its position on the list (we could consider as an unique LINE). On the other hand, on matrices the elements are identified by two or more indexes that, working together, indicate the position of the item in the collection. As for two-dimension matrices, we consider that the items refer themselves as LINES and COLUMNS. To dimensions equal or up to three, we give no names to the indexes.

Observation: In C#, as in the majority of the programming languages, the indexes are "zero-based", which means they starting counting up from zero, and not from one, as we are used to in our daily lives. Figure 1: Illustration of an array of integer numbers with indexes in the top Figure 2: Illustration of a matrix of letters with marked indexes Figure 3: Illustration of an tridimensional array in marked indexes

In the Pictures 1, 2 and 3 we have represented the arrays of 1, 2 and 3 dimensions, respectively. In the first example, we have an array where each element consists of an integer number and which index is shown atop. For instance, the element of index equals to 0 possesses value 9.

In picture 2, we have illustrated one matrix (two dimensions) of letters, which indexes of the lines, horizontal ones, and columns, vertical ones, are shown marked atop and in the left side, respectively. As it has already been said, each element is identified by two indexes (lines and columns), for example, the element of indexes 1 and 1 has the value "Q", while the element in the position (3,2) values "J".

The picture 3, as it is, shows what would be a tridimensional array. In this case, however, we have not defined values to the elements, just gave some items different colors as we could reference them. In this case, each element is identified by three indexes. In the picture, the element of indexes (0,0,0) is orange colored, while the element (0,2,1) is the green one, and the yellow element (atop), possesses indexes (2,1,1)

Observation: such for matrices as for tridimensional structures, we indicate the indexes saying first ther line, second the column, and then the other dimensions.

Observation: As said before, we cannot illustrate and visualize structures with more than 3 dimensions, or make references to objects of our daily lives. The study of other dimensions in the real universe is done on advanced phisics.

When we declare an array of a determinate type, it is reserved a sequencial region on the memory with enough capacity to store all the items of the list. It means, a multiple quantity of bytes of the size of the type is dedicated to the storing of the items of the array. For instance, knowing that a variable of the int type occupied 4 bytes in the memory, if we declare an array with capacity to 3 element of this type, we'll be keeping 4x3=12 bytes in thee memory (in a sequencial way). Figure 4: Illustration of the region of the memory used by an array

In the picture 4, we have an illustration of what would be a region of the memory of 20 sequential bytes. The red squares indicate one possible form of allocation of space to the storage of the array of the past paragraph. Let us see that were reserved 12 bytes, from 002 to the 013. This space is only freed when the array is destroyed (or by a process od dynamic liberation of memory, that we won't see on the article, but that's frequently used by C programs).

As the array, every element individually have an address in the memory in which are searched their informations when the access to them is requested by the system. This address is given by the location of the first byte of the sequence, it means, the array address is the byte 001 in the memory. As each element occupies 4 bytes, their addresses are 001, 006 and 010.

When we access an element of an array, its position in the memory is located by the array address as a whole and the quantity of bytes occupied by the type of the element along with its index. For example, if we wished to access the second element of the array above, its position would be given by: 002 + 4x1 = 006. Where: 002 is the address of the array; 4 is the quantity of bytes occupied by an integer, and 1 is the index of the element that we want to access.

Observation: On some cases, that are reserved a few more bytes beyond of the explained here. This is done because of the internal behavior of the array, that sometimes requires larger spaces to fulfill certain operations.

### "Jagged" Arrays

"The named 'jagged arrays'are one more type of array, where each element is an array". Simple definition, simple use.

Giving an example it maybe be easier to understand: let's assume we have an array that stores classes of a school and, for each class, we have a different number of students, from which we need to store the code. We could use one matrix where the lines would represent the class and the columns would represent the students, however, we would be using a fixed number of students, equal to all the classes, what does not attend our needs. Here enter the jagged arrays. We could have an array that stores the quantity of classes (a known number) and each element is an array, which length varies and that we could've define individually. Below we shall see how to declare and initialize the many types of arrays in C#.

### Arrays in C#: declaration

The declaration of arrays in the C# language is quite simple. Let us see the listings 1,2 and 3.

Listing 1: Declaration of an array in C#

```//Generic syntax: type[] name;
int[] numbers; // Integer values array
string[] names; // String array
```

Listing 2: Declaration of a matrix in C#

```//Generic syntax: type[,] name;
int[,] bidimensionalArray;
decimal[, ,] tridimensionalArray;
```

Listing 3: Declaration of a jagged array in C#

```//Generic syntax: type[][] name;
int[][] integerArray;
float[][] decimalArray;
```

The declaration is not a complex process, the most important part is the initialization, what we shall see below.

### C# arrays: Initialization

The initialization of arrays in the C# language can be done in two ways: in the moment of the declaration and after the declaration. We'll see on the listings 5, 6, and 7 how to proceed with that initialization ion the moment of the declaration.

Listing 4: Array initialization in the moment of the declaration

```int[] odds = new int[] { 1, 3, 5, 7, 9 };
//or
int[] odds = { 1, 3, 5, 7, 9 };
```

Listing 5: Initialization of matrix in the moment of declaration

```int[,] matrix = new int[,] { { 1, 2 }, { 3, 4 } };
//ou
int[,] matrix = { { 1, 2 }, { 3, 4 } };
```

Listing 6: Jagged array initialization in the moment of the declaration

```int[][] jagged1 = new int[][]
{
new int[] {0,1,2,3},
new int[] {4,5,6,7,8,9},
new int[] {10,20,30,40}
};
//or
int[][] jagged1 =
{
new int[] {0,1,2,3},
new int[] {4,5,6,7,8,9},
new int[] {10,20,30,40}
};
```

May the values have not been defined in the moment of their declaration, we can after access each element and give it a value, what exemplified on the listings 8, 9 and 10.

Listing 7: Initializing elements of an array individually

```int[] intArray = new int;
intArray = 10;
intArray = 25;
intArray = 99;
```

Listing 8: Initializing elements of a matrix individually

```string[,] matrix = new string[2, 2];
matrix[0, 0] = "C#";
matrix[0, 1] = "Delphi";
matrix[1, 0] = "Java";
matrix[1, 1] = "VB.NET";
```

Listing 9: Initializing elements of a jagged array individually

```int[][] jagged = new int[];
jagged = new int[] { 0, 1, 2, 3};
jagged = new int[] { 4, 5, 6, 7, 8, 9 };
jagged = new int[] { 10, 20};
```

As we saw, initialize the elements of an array isn't a complicated process. The way how that initialization is going to happen depends, in general, of the situation. Let's see now a few practical examples of the utilization of this data structure so simple, and at the same time, so usefull in the world of computing programming.

### C# arrays: Practical examples

On the listing 11 we'll use one array to store 10 numbers informed by the user and, at the end, exhibit those that are below the media of the group.

Listing 10: Practical example with an array

```int[] values = new int;
decimal sum = 0, avg = 0;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(String.Format("Enter the element with index {0}:", i));
sum += values[i];
}
avg = sum / 10;
for (int i = 0; i < 10; i++)
{
if(values[i] < avg)
Console.WriteLine(String.Format("The element with index {0}, which value is {1}, is below the average.", i, values[i]));
}
```

On the listing 12, we'll use one matrix to set up one "bingo card", where the numbers are informed by the user.

Observation: "Bingo" is a game where someone calls a number at random, raffling them, and you have a card with a few random numbers. If you have in your card the number called, you check it. The first one to check all numbers wins.

Listing 11: Practical example with matrices

```int[,] bingo = new int[5,5];

for (int i = 0; i < 5; i++ )
{
for (int j = 0; j < 5; j++)
{
Console.WriteLine(String.Format("Enter the element ({0},{1})", i, j));
}
}
```

And ending, we'll use one jagged array to store classes with many students per each.

Listing 12: Practical example with a Jagged Array

```Console.WriteLine("Enter the number of classes: ");
string[][] classes = new string[num_classes][];
for (int i = 0; i < num_classes; i++ )
{
Console.WriteLine("Enter the number of students on the class {0}:", i);
classes[i] = new string[num_students];
for (int j = 0; j < num_students;j++ )
{
Console.WriteLine("Enter the name of the student {0}:", j);
}
}
```

In the up above examples we used only the tie FOR, but the other structures of iteration as WHILE and FOREACH can be equally used. The choice of them will depend on the situation.

We conclude hare this article that had as objective to make a general approach about arrays, treating since their theoretical definition, the way they're stored in the memory, how we access them and, finalizing, we saw many practical examples of utilization.

Thanks the attention of the reader. See you in the next opportunity. Microsoft MVP, Bachelor in Science And Technology, Editor and Consultant at DevMedia with more than 7 years of experience in software development.

What did you think of this post?
Services

Related Posts

[Close] See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US\$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US\$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US\$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!