using System; public class Exercise { static int Main() { var number1 = 12.44; var number2 = 525.38; var number3 = 6.28; var number4 = 2448.32; var 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.
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: DataType[] VariableName = new DataType[Number]; Alternatively, you can use the var or the dynamic keyword to create an array. The formula to use would be: var VariableName = new DataType[Number]; dynamic VariableName = new DataType[Number]; In these formulas, the DataType 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 VariableName. 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; } }
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.
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.
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, the know the number of items that an array contines, get the value of the Length property.
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.2204D; var distance = 982.84D; var level = 27D; var quantity = 237957.704D; 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.414D;
var e = 2.718D;
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. If the array is made of integers, you can use decimal, hexadecimal values, or a combination of both. Here is an example: using System; public class Exercise { public static int Main() { var red = 0xFF0000; var someColor = 0x800000; var colors = new int[] { 2510, red, 818203, someColor, 0xF28AC }; return 0; } } 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.85D; var house2Value = 685770.00D; var conparisons = new bool[] { 25 < 10, house1Value == house2Value, true }; return 0; } } As we will see when studying arrays and classes, you can use this technique to create an array of dates, times, or date and time values. Here is an example: using System; public class Exercise { public static int Main() { var dateHired = new DateTime(1998, 10, 08); var independenceDay = new DateTime(1960, 1, 1); var Dates = new DateTime[] { dateHired, independenceDay }; 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; } }
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.
We saw how you can use the square brackets to access each member of the array one at a time. That technique allows you to access one, a few, or each member. If you plan to access all members of the array instead of just one or a few, you can use the for loop. The formula to follow is: for(DataType Initializer; EndOfRange; Increment) Do What You Want; In this formula, the for keyword, the parentheses, and the semi-colons are required. The DataType factor is used to specify how you will count the members of the array. The Initializer specifies how you would indicate the starting of the count. As seen in Lesson 12, this initialization could use an initialized int-based variable. The EndOfRange specifies how you would stop counting. If you are using an array, it should combine a conditional operation (<, <=, >, >=, or !=) with the number of members of the array minus 1. The Increment factor specifies how you would move from one index to the next. 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 }; for (var i = 0; i < 5; i++) Console.WriteLine(numbers[i]); return 0; } } This would produce: 12.44 525.38 6.28 2448.32 632.04 Press any key to continue . . . When using a for loop, you should pay attention to the number of items you use. If you use a number n less than the total number of members - 1, only the first n members of the array would be accessed. 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 }; for (var i = 0; i < 3; i++) Console.WriteLine("Number: {0}", numbers[i]); return 0; } } This would produce: Number: 12.44 Number: 525.38 Number: 6.28 Press any key to continue . . . On the other hand, if you use a number of items higher than the number of members minus one, the compiler would throw an IndexOutOfRangeException exception. 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 }; for (var i = 0; i < 12; i++) Console.WriteLine("Number: {0}", numbers[i]); return 0; } } This would produce:
After the nasty dialog box, you would get:
Therefore, when the number of items is higher than the number of members - 1, the compiler may process all members. Then, when it is asked to process members beyond the allowed range, it finds out that there is no other array member. So it gets upset. You could solve the above problem by using exception handling to handle an IndexOutOfRangeException exception. 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 }; try { for (var i = 0; i < 12; i++) Console.WriteLine("Number: {0}", numbers[i]); } catch (IndexOutOfRangeException) { Console.WriteLine("You tried to access values beyond " + "the allowed range of the members of the array."); } return 0; } } This would produce: Number: 12.44 Number: 525.38 Number: 6.28 Number: 2448.32 Number: 632.04 You tried to access values beyond the allowed range of the members of the array. Press any key to continue . . . This solution should not be encouraged. Fortunately, C# and the .NET Framework provide better solutions.
In a for loop, you should know the number of members of the array. If you do not, the C# language allows you to let the compiler use its internal mechanism to get this count and use it to know where to stop counting. To assist you with this, C# provides the foreach operator. To use it, the formula to follow is: foreach (type identifier in expression) statement The foreach and the in keywords are required. The first factor of this syntax, type, can be var or the type of the members of the array. It can also be the name of a class as we will learn in Lesson 23. The identifier factor is a name of the variable you will use. The expression factor is the name of the array variable. The statement is what you intend to do with the identifier or as a result of accessing the member of the array. Like a for loop that accesses all members of the array, the foreach operator is used to access each array member, one at a time. 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 }; foreach(var n in Numbers) Console.WriteLine("Number: {0} ", n); return 0; } } This would produce: Employees Records Employee Name: Joan Fuller Employee Name: Barbara Boxen Employee Name: Paul Kumar Employee Name: Bertrand Entire
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.
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:
After creating an anonymous array, you can access each member using its index. Here is an example that uses a for loop: using System; using System.Linq; public class Exercise { static int Main() { var friends = new[] { "Mark", "Frank", "Charlotte", "Jerry" }; for (var i = 0; i < 4; i++) Console.WriteLine("Friend: {0}", friends[i]); return 0; } } This would produce: Friend: Mark Friend: Frank Friend: Charlotte Friend: Jerry Press any key to continue . . . In the same way, you can use a foreach statement to access each member of the array. Here is an example: using System; public class Exercise { static int Main() { var friendlies = new[] { "Mark", "Frank", "Charlotte", "Jerry" }; for (var i = 0; i < 4; i++) Console.WriteLine("Friend: {0}", friendlies[i]); Console.WriteLine("-----------------------------------"); var qualifications = new[] { true, true, false, true, false }; foreach (var qualifies in qualifications) Console.WriteLine("The Member Qualifies: {0}", qualifies); Console.WriteLine("-----------------------------------"); return 0; } } This would produce: Friend: Mark Friend: Frank Friend: Charlotte Friend: Jerry ----------------------------------- The Member Qualifies: True The Member Qualifies: True The Member Qualifies: False The Member Qualifies: True The Member Qualifies: False ----------------------------------- Press any key to continue . . .
Because an array is a list of items, it could include values that are not useful in all scenarios. For example, having an array made of too many values, at one time you may want to isolate only the first n members of the array, or the last m members of the array, or a range of members from an index i to an index j. Another operation you may be interested to perform is to find out if this or that value exists in the array. One more interesting operation would be to find out what members or how many members of the array respond to this or that criterion. All these operations are useful and possible with different techniques.
Consider the following program: using System; public class Exercise { static int Main() { var numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 }; for (var i = 0; i < 10; i++) Console.WriteLine("Number: {0}", numbers[i]); return 0; } } This would produce: Number: 102 Number: 44 Number: 525 Number: 38 Number: 6 Number: 28 Number: 24481 Number: 327 Number: 632 Number: 104 Press any key to continue . . . Imagine you want to access only the first n members of the array. To do this, you can use an if conditional statement nested in a for or a foreach loop. Here is an example that produces the first 4 values of the array: using System; public class Exercise { static int Main() { var numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 }; for (var i = 0; i < 10; i++) if (i < 4) Console.WriteLine("Number: {0}", numbers[i]); return 0; } } This would produce: Number: 102 Number: 44 Number: 525 Number: 38 Press any key to continue . . . You can use the same technique to get the last m members of the array. You can also use a similar technique to get one or a few values inside of the array, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array: using System; public class Exercise { static int Main() { var numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 }; for (var i = 0; i < 10; i++) if (numbers[i] % 5 == 0) Console.WriteLine("Number: {0}", numbers[i]); return 0; } } This would produce: Number: 525 Press any key to continue . . .
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||