Introduction to Arrays |
|
A Series of Similar Items |
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: |
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() { 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 keyword to create an array. The formula to use would be: var VariableName = new DataType[Number]; In these formulas, the DataType factor 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 in Lesson 23. 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 declaring an array instead of a regular variable. The new operator allows the compiler to reserve memory. The Number factor 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 { static void Main() { double numbers = new double[5]; } } Using the var keyword, this array can also be declared as follows: using System; public class Exercise { static void Main() { var Numbers = new double[5]; } }
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 0 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 void 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; } } 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 { static void Main() { var Numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; } } 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 { static void Main() { var Numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; } } If you leave the square brackets empty, the compiler will figure out the number of items.
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 { static void Main() { var Area = 97394.2204D; var Distance = 982.84D; var Level = 27D; var Quantity = 237957.704D; var Measures = new double[] { Area, Distance, Level, Quantity }; } } The values can also come from constant variables. Here is an example: using System; public class Exercise { static void Main() { const double PI = 3.141592653; var SqureRootOf2 = 1.414D; var e = 2.718D; const double RadiusOfEarth = 6370; // km var ln2 = 0.6931; var Measures = new double[] { PI, SqureRootOf2, e, RadiusOfEarth, ln2 }; } } 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 { static void 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 }; } } 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 { static void Main() { var Red = 0xFF0000; var SomeColor = 0x800000; var Colors = new int[] { 2510, Red, 818203, SomeColor, 0xF28AC }; } } 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 { static void Main() { var FullTimeStudents = new bool[] { true, true, true, false, true, false }; } } As stated already, each values 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 { static void Main() { var House1Value = 460885.85D; var House2Value = 685770.00D; var Conparisons = new bool[] { 25 < 10, House1Value == House2Value, true }; } } 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 { static void Main() { var DateHired = new DateTime(1998, 10, 08); var IndependenceDay = new DateTime(1960, 1, 1); var Dates = new DateTime[] { DateHired, IndependenceDay }; } } |
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 don't, 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; using System.Linq; 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; using System.Linq; 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; using System.Linq; 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; using System.Linq; 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 . . .
|
|
||
Previous | Copyright © 2008-2016, FunctionX, Inc. | Next |
|