A Series of Similar Items

Introduction

Imagine you want to create a program that would use a series of numbers. In algebra, we represent such a series as follows: X1, X2, X3, X4, X5. You can also represent a list of names as follows:

 Alex Gaston Hermine Jerry

So far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:

```using System;

public class Exercise
{
static int Main()
{
double number1 = 12.44;
double number2 = 525.38;
double number3 = 6.28;
double number4 = 2448.32;
double number5 = 632.04;

return 0;
}
}```

Instead of using individual variables that share the same characteristics, you can group them in an entity like a regular variable. This group is called an array. Therefore, an array is a series of items of the same kind. It could be a group of numbers, a group of cars, a group of words, etc but all items of the array must be of the same type.

Practical Learning: Introducing Arrays

1. Start Microsoft Visual Studio
2. To create an application, on the main menu, click File -> New -> Project
3. In the middle list, click Empty Project (.NET Framework)
4. Set the Name to VideoCollection1
5. Click OK
6. To create a file, on the main menu, click Project -> Add New Item...
7. In the middle list, click Code File
8. Change the Name to VideoCollection and click Add

Array Creation

Before creating an array, you must first decide the type its items will be made of. Is it a group of numbers, a group of chairs, a group of buttons on a remote control? This information allows the compiler to know how much space each item of the group will require. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of each item that makes up the series, you must use a common name to identify them. The name is simply the same type of name you would use for a variable as we have used so far. The name allows you and the compiler to identify the area in memory where the items are located.

Thirdly, you must specify the number of items that will constitute the group. For the compiler to be able to allocate an adequate amount of space for the items of the list, once it knows how much space each item will require, it needs to know the number of items so an appropriate and large enough amount of space can be reserved. The number of items of an array is included in square brackets, as in [5].

An array is considered a reference type. Therefore, an array requests its memory using the new operator. Based on this, one of the formulas to declare an array is:

`data-type[] variable-name = new data-type[Number];`

Alternatively, you can use the var or the dynamic keyword to create an array. The formula to use would be:

```var variable-name = new data-type[Number];
dynamic variable-name = new data-type[Number];```

In these formulas, the data-type can be one of the types we have used so far (char, int, float, double, decimal, string, etc). It can also be the name of a class as we will learn. Like a normal variable, an array must have a name, represented in our formula as variable-name. The square brackets on the left of the assignment operator are used to let the compiler know that you are creating an array instead of a regular variable. The new operator allows the compiler to reserve memory. The Number is used to specify the number of items of the list.

Based on the above formula, here is an example of an array variable:

```using System;

public class Exercise
{
public static int Main()
{
double[] numbers = new double[5];
}
}```

Here are examples using the var or the dynamic keyword:

```using System;

public class Exercise
{
static int Main()
{
double[] numbers = new double[5];
var distances = new float[8];
dynamic values = new int[3];

return 0;
}
}```

Practical Learning: Creating an Array

1. In the empty document, type the following:
```public class VideoCollection
{
public static int Main()
{
int[]   shelfNumbers = new int[10];
string[] titles = new string[10];
string[] directors = new string[10];
int[]    Lengths = new int[10];
string[] ratings = new string[10];
double[] prices = new double[10];

return 0;
}
}```

Introduction to the Array Class

To support arrays, the .NET Framework provides a class named Array. The Array class is defined in the System namespace. Whenever you create or use an array, it is actually an object of type Array. In this and the next two lessons, we will study what an array is, as a programming language concept. We will see the different ways you can use and manage an array. In Lesson 45, we will present more details about the Array class. We will find out that this class provides all the functionality necessary to create and manage an array.

Initializing an Array

Introduction

When creating an array, you can specify the number of items that make up its list. Each item of the series is referred to as a member or an element of the array. Once the array has been created, each one of its members is initialized with a default value. Most, if not all, of the time, you will need to change the value of each member to a value of your choice. This is referred to as initializing the array.

An array is primarily a variable; it is simply meant to carry more than one value. Like every other variable, an array can be initialized. There are two main techniques you can use to initialize an array. If you have declared an array as done above, to initialize it, you can access each one of its members and assign it a desired but appropriate value.

In algebra, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A C# (like a C/C++) array is zero-based. This means that the first member of the array has an index of 0, the second has an index of 1, and so on. In algebra, the series would be represented as X0, X1, X2, X3, and X4.

In C#, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[5];

numbers[0] = 12.44;
numbers[1] = 525.38;
numbers[2] = 6.28;
numbers[3] = 2448.32;
numbers[4] = 632.04;

return 0;
}
}```

The value between square brackets must be known. This time, we have used constants, but this is not always the case. The rule is that, at the time you open the square brackets, the value must be known, even if it is not a constant. For example, the value can be returned from a method. Here is an example:

```using System;

public class Exercise
{
static int GetIndex()
{
return 2;
}

public static int Main()
{
var numbers = new double[5];

numbers[0] = 12.44;
numbers[1] = 525.38;
numbers[GetIndex()] = 6.28;
numbers[3] = 2448.32;
numbers[4] = 632.04;

return 0;
}
}```

Besides this technique, you can also initialize the array as a whole when declaring it. To do this, on the right side of the declaration, before the closing semi-colon, type the values of the array members between curly brackets and separated by a comma. Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
var numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

return 0;
}
}```

If you use this second technique, you don't have to specify the number of items in the series. In this case, you can leave all square brackets empty:

```using System;

public class Exercise
{
public static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

return 0;
}
}```

If you leave the square brackets empty, the compiler will figure out the number of items.

Practical Learning: Initializing Some Arrays

• To initialize the arrays, change the file as follows:
```public class VideoCollection
{
public static int Main()
{
int[] shelfNumbers = new int[]
{
2985, 8024, 5170, 1304, 9187,
1193, 3082, 8632, 4633, 9623
};
string[] titles = new string[]
{
"The Distinguished Gentleman",
"A Perfect Murder", "Chalte Chalte",
"Ransom", "Not Another Teen Movie",
"Sneakers", "Born Invincible", "Hush"
};
string[] directors = new string[]
{
"Jonathan Lynn", "Andrew Davis", "Aziz Mirza",
"Ron Howard", "Joel Gallen", "Shivram Yadav",
"Barry Sonnenfeld", "Paul Alden Robinson",
"Unknown", "Jonathan Darby"
};
int[] lengths = new int[]
{
112, 108, 145, 121, 100, 0, 105, 126,  90,  96
};
string[] ratings = new string[]
{
"R", "R", "N/R", "R", "Unrated",
"N/R", "R", "PG-13", "N/R", "PG-13"
};
double[] prices = new double[]
{
14.95, 19.95, 22.45, 14.95, 9.95,
17.50,  9.95,  9.95,  5.95, 8.75D
};

return 0;
}
}```

The Length of an Array

We saw that if you declare an array variable but don't initialize it, you must specify the number of elements of the array. This number is passed inside the second pair of square brackets, as a constant integer. Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[5];

return 0;
}
}```

If the array exists already, to assist you with finding out the number of elements in it, the Array class provides a read-only property named Length:

`public int Length { get; }`

Therefore, to know the number of items that an array contais, get the value of the Length property.

Other Techniques of Initializing an Array

We have initialized our arrays so far with values we specified directly in the curly brackets. If you have declared and initialized some variables of the same type, you can use them to initialize an array. Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
var area = 97394.2204;
var distance = 982.84;
var level = 27;
var quantity = 237957.704;

var Measures = new double[] { area, distance, level, quantity };

return 0;
}
}```

The values can also come from constant variables. Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
const double PI = 3.141592653;
var squareRootOf2 = 1.414;
var e = 2.718;
const double radiusOfEarth = 6370; // km
var ln2 = 0.6931;

var Measures = new double[] { PI, squareRootOf2, e, radiusOfEarth, ln2 };

return 0;
}
}```

The values can also come from calculations, whether the calculation is from an initialized variable or made locally in the curly brackets. Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
const double densityOfWater = 1000; // kg/m3 ;
var massOfEarth = 5.98 * 10e24; // kg
var earthMoonDistance = 2.39 * 10e5; // miles

var Measures = new double[]
{
densityOfWater, 9.30 * 10.7, massOfEarth, earthMoonDistance
};

return 0;
}
}```

The rule to follow is that, at the time the array is created, the compiler must be able to know exactly the value of each member of the array, no guessing.

All of the arrays we have declared so far were using only numbers. The numbers we used were decimal constants.

An array can have types of values of any of the data types we have used so far. The rule to follow is that all members of the array must be of the same type. For example, you can declare an array of Boolean values, as long as all values can be evaluated to true or false. Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
var fullTimeStudents = new bool[] { true, true, true, false, true, false };

return 0;
}
}```

As stated already, each value of a Boolean array must be evaluated to true or false. This means that you can use variables or expressions as members of the array. Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
var house1Value = 460885.85;
var house2Value = 685770.00;

var conparisons = new bool[] { 25 < 10, house1Value == house2Value, true };

return 0;
}
}```

An index can be returned from a method. Here is an example:

```using System;

public class Exercise
{
static int GetIndex()
{
return 2;
}

static double GetDistance()
{
return 632.04;
}

public static int Main()
{
var numbers = new double[5];

numbers[0] = 12.44;
numbers[1] = 525.38;
numbers[GetIndex()] = 6.28;
numbers[3] = 2448.32;
numbers[4] = GetDistance();

return 0;
}
}```

As a result, both the index and the value can come from methods. Here is an example:

```using System;

public class Exercise
{
static int GetIndex()
{
return 4;
}

static double GetDistance()
{
return 632.04;
}

public static int Main()
{
var numbers = new double[5];

numbers[0] = 12.44;
numbers[1] = 525.38;
numbers[2] = 6.28;
numbers[3] = 2448.32;
numbers[GetIndex()] = GetDistance();

return 0;
}
}```

Accessing the Members of an Array

Introduction

After initializing an array, which means after each of its members has been given a value, you can access a member of the array to get, manipulate or even change its value. To access a member of the array, you use the square brackets as we saw above. As done for normal variables, one of the reasons of accessing a member of an array would be to display its value on the console screen, which can be done by passing it to a Console.Write() or a Console.WriteLine() method. Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

Console.Write(numbers[3]);

return 0;
}
}```

In the same way, you can use the curly brackets notation to display the value of a member:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

Console.Write("Number: {0} ", numbers[3]);

return 0;
}
}```

In the same way, you can access 1, a few or all members of the array.

Practical Learning: Using the Members of an Array

1. To show the values of a member of an array, change the VideoCollection.cs file as follows:
```using System;

public class VideoCollection
{
public static int Main()
{
int[] shelfNumbers = new int[]
{
2985, 8024, 5170, 1304, 9187, 1193, 3082, 8632
};

. . . No Change

double[] prices = new double[]
{
14.95, 19.95, 22.45, 14.95, 9.95,
17.50,  9.95,  9.95,  5.95, 8.75D
};

Console.Title = "Video Collection";

Console.WriteLine("===============================");
Console.WriteLine("Video Information");
Console.WriteLine("-------------------------------");
Console.WriteLine("Shelf #:  {0}", shelfNumbers[1]);
Console.WriteLine("Title:    {0}", titles[1]);
Console.WriteLine("Director: {0}", directors[1]);
Console.WriteLine("Length:   {0} minutes", lengths[1]);
Console.WriteLine("Rating:   {0}", ratings[1]);
Console.WriteLine("Price:    {0}", prices[1]);
Console.WriteLine("===============================");

return 0;
}
}```
2. To execute the application, press F5:
```===============================
Video Information
-------------------------------
Shelf #:  8024
Title:    A Perfect Murder
Director: Andrew Davis
Length:   108 minutes
Rating:   R
Price:    19.95
===============================
Press any key to continue . . .```

Anonymous Arrays

Introduction

In previous sections, when creating an array, we were specifying its type. As seen in our introduction to variables, a good feature of the var keyword is that, when using it to declare and initialize a variable, you ask the compiler to figure out what type of data the variable is holding. This concept is also valid for an array.

An anonymous array is an array variable whose type is left to the compiler to determine, based on the types of values of the array.

Creating an Anonymous Array

As done for variables so far, when creating an array, you can use the var keyword, initialize the array, but not specify its data type. The formula to use is:

`var ArrayName = new[] { Initialization };`

The formula is almost similar to that of a normal array, with keywords and operators you are already familiar with. The ArrayName factor is the name of the variable. Notice that the new keyword is directly followed by the square brackets. In the curly brackets, you must initialize the array by providing the necessary values. For the compiler to be able to figure out the type and amount of memory to allocate for the array variable, all values must be of the same type or the same category:

• If each value is a number without a decimal part, the compiler checks their rang. Here is an example:
```using System;

public class Exercise
{
static int Main()
{
var naturals = new[] { 2735, 20, 3647597, 3408, 957 };

return 0;
}
}```
• If the values are numeric but at least one of them includes a decimal part, the compiler concludes that the array is made of floating-point numbers. Here is an example:
```using System;

public class Exercise
{
static int Main()
{
var singles = new[] { 1244, 525.38, 6.28, 2448.32, 632.04 };
var doubles = new[] { 3.212, 3047.098, 732074.02, 18342.3579 };
var values = new[] { 17.230, 4808237, 222.4203, 948.002009 };

return 0;
}
}```
• If the members are made of true and false values, then compiler will allocate memory for Boolean values for the array. Here is an example:
```using System;

public class Exercise
{
static int Main()
{
var qualifications = new[] { true, true, false, true, false };

return 0;
}
}```
• If the members contain values included in single-quotes, the array will be treated as a series of characters. Here is an example:
```using System;
using System.Linq;

public class Exercise
{
static int Main()
{
var categories = new[] { 'C', 'F', 'B', 'C', 'A' };

return 0;
}
}```
• If the values of the members are included in double-quotes, then the array will be considered a group of strings. Here is an example:
```using System;
using System.Linq;

public class Exercise
{
static int Main()
{
var friends = new[] { "Mark", "Frank", "Charlotte", "Jerry" };

return 0;
}
}```

Practical Learning: Ending the Lesson