Accessing Individual Array Elements

   


An individual array element is accessed in the same manner as an individual character of a string variable by writing the array variable name followed by a pair of square brackets containing the index value of the element. The following line

 accountBalances[0] = 1000m; 

assigns the value 1000 of type decimal to the first element of array elements contained in the object referenced by accountBalances. The index can be any numerical expression with a non-negative value of a type implicitly convertible to type int, and must be evaluated to a value less than the length of the array.

Note

graphics/common.gif

The index values of the individual array elements begin at zero not one; the array is said to be zero based. Thus, accountBalances[0] represents the first array element of the collection represented by accountBalances. The index of the last array element is equal to the array length minus one. Consequently, accountBalances[4] refers to the fifth and last array element in our example.

Sometimes, the first array element (accountBalances[0]) is mistakenly referred to as the "zero'eth" element. The problem with this name appears when we then have to find a suitable name for accountBalances[1]. The logical but incorrect name would be "first element." If, instead of this incorrect naming scheme, you get into the habit of calling accountBalances[0] for the first element, you should quickly get accustomed to calling accountBalances[4] for the fifth element.


Note

graphics/common.gif

Recall that strings are immutable. This prevents us from changing any of the characters in a string. On the other hand, the array is mutable, allowing us to assign values to individual elements of an array.


accountBalances[0] can be regarded as any other variable of type decimal in the sense that we can assign and retrieve values from this element and let it take part in any suitable expression. For example, to print the value of a ten percent interest from accountBalances[0], we can write the following:

 Console.WriteLine(accountBalances[0] * 0.1m); 

Let's put all the pieces we have mentioned so far together into a simple program. The source code presented in Listing 10.1 declares an array of five account balances. It lets the user assign an amount to the first two array elements and adds a ten percent interest to those. The amounts of these two first account balances are finally printed out. To keep the source code short, the three remaining account balances accountBalances[2], accountBalances[3], and accountBalances[4] are not accessed in this program.

Listing 10.1 SimpleAccountBalances.cs
01: using System; 02: 03: class SimpleAccountBalances 04: { 05:     public static void Main() 06:     { 07:         const decimal interestRate = 0.1m; 08:         decimal [] accountBalances; 09: 10:         accountBalances = new decimal [5]; 11: 12:         Console.WriteLine("Please enter two account balances: "); 13:         Console.Write("First balance: "); 14:         accountBalances[0] = Convert.ToDecimal(Console.ReadLine()); 15:         Console.Write("Second balance: "); 16:         accountBalances[1] = Convert.ToDecimal(Console.ReadLine()); 17: 18:         accountBalances[0] = accountBalances[0] + accountBalances[0] * interestRate; 19:         accountBalances[1] = accountBalances[1] + accountBalances[1] * interestRate; 20: 21:         Console.WriteLine("New balances after interest: "); 22:         Console.WriteLine("First balance: { 0:C} ", accountBalances[0]); 23:         Console.WriteLine("Second balance: { 0:C} ", accountBalances[1]); 24:     } 25: } Please enter two account balances: First balance: 1000<enter> Second balance: 2000<enter> New balances after interest: First balance: $1,100.00 Second balance: $2,200.00 

Line 8 declares accountBalances to hold a reference to an array with array elements of type decimal. Line 10 instantiates an object of class System.Array, allocates space for it in memory, and assigns its reference to the accountBalances variable. Lines 14 and 16 assign the amounts provided by the user to the array elements with index 0 and 1, respectively. If the user enters the amounts 1000 and 2000, as shown in the sample output, the array object can be depicted as shown in Figure 10.3, which further shows how each array element is accessed syntactically. Lines 18 and 19 add the interest (determined by the const interestRate in line 7) to the two account balances. Their values after this interest update are finally printed out in lines 22 and 23.

Figure 10.3. The two values assigned to accountBalances.
graphics/10fig03.gif

The syntax used for accessing individual array elements, as presented earlier and used in Listing 10.1 is formalized in Syntax Box 10.2.

Syntax Box 10.2 Accessing Array Elements

 Array_element_access::= <Array_identifier> [<Numerical_expression> graphics/ccc.gif] 

Notes:

  • The square brackets [] do not indicate an option in this case (then they would have looked like []) but the actual square brackets that must enclose the index in the form of a <Numerical_expression>.

  • <Numerical_expression> can be any expression with a type implicitly convertible to type int. According to Figure 6.17, of Chapter 6, "Types Part I: The Simple Types," showing the implicit conversion paths of the simple numeric types in C#, it is possible to use expressions of type sbyte, byte, short, ushort, and char. Any other type must either have a user-defined implicit conversion path specified, or be explicitly converted with the cast operator.

Note

graphics/common.gif

It is important to differentiate between the three different contexts in which the square brackets are used in relation to arrays:

  • To declare an array variable

     decimal [] accountBalances; 
  • To enclose the array length when creating an array object

     new decimal [5] 
  • To access individual array elements

     accountBalances[0] 


Listing 10.1 showed you how to use the array element reference accountBalances[0] in a program just like any other variable of type decimal. Even though this is useful as an initial demonstration of how individual array elements are accessed and used, it doesn't demonstrate the real power of arrays. To that end, we can combine the array with a loop statement, such as in Listing 10.2. The functionality of the program is very similar to that of Listing 10.1, but the implementation differs significantly. By combining the for loop construct with the array accountBalances, the program

  • Allows the user to enter five account balances

  • Adds interest to each single account balance

  • Prints out the resulting five balances

Listing 10.2 AccountBalanceTraversal.cs
01: using System; 02: 03: class AccountBalanceTraversal 04: { 05:     public static void Main() 06:     { 07:         const decimal interestRate = 0.1m; 08: 09:         decimal [] accountBalances; 10: 11:         accountBalances = new decimal [5]; 12: 13:         Console.WriteLine("Please enter { 0}  account balances:",  graphics/ccc.gifaccountBalances.Length); 14:         for (int i = 0; i < accountBalances.Length; i++) 15:         { 16:             Console.Write("Enter balance with index { 0} : ", i); 17:             accountBalances[i] = Convert.ToDecimal(Console.ReadLine()); 18:         } 19: 20:         Console.WriteLine("\nAccount balances after adding interest\n"); 21:         for (int i = 0; i < accountBalances.Length; i++) 22:         { 23:             accountBalances[i] = accountBalances[i] 24:                 + (accountBalances[i] * interestRate); 25:             Console.WriteLine("Account balance with index { 0} : { 1:C} ", 26:                 i, accountBalances[i]); 27:         } 28:     } 29: } Please enter five account balances: Enter balance with index 0: 10000<enter> Enter balance with index 1: 20000<enter> Enter balance with index 2: 15000<enter> Enter balance with index 3: 50000<enter> Enter balance with index 4: 100000<enter> Account balances after adding interest Account balance with index 0: $11,000.00 Account balance with index 1: $22,000.00 Account balance with index 2: $16,500.00 Account balance with index 3: $55,000.00 Account balance with index 4: $110,000.00 

Once again, accountBalances refers to an array object holding 5 decimal values (lines 9 and 11).

The for loop spanning lines 14 18 is repeated five times. The variable i starts at 0 and is incremented by 1 for every repeated execution of the loop body. Execution stops when the loop condition i < accountBalances.Length becomes false. accountBalances.Length is equivalent to the Length property found in the string class, and is just one of many useful properties and methods built into an object of type System.Array. It returns the array length, in this case 5, and causes i < accountBalances.Length to be false when i is equal to 5. Consequently i is equal to 4 when the loop body is executed for the last time. This fits nicely with the functionality we want to implement with the loop body in lines 16 and 17, to repeatedly get a new amount from the user and insert it into an array element with an index starting at 0 and incremented by 1 for every new amount. All 5 array elements: accountBalances[0], accountBalances[1], accountBalances[2], accountBalances[3], and accountBalances[4] are each assigned a new amount from the user.

The for loop of lines 21 27 contains exactly the same loop initialization, loop condition, and loop update as the previous for loop, resulting in the same loop behavior. Through the statement in lines 23 and 24, each account balance gets interest added to its amount. The balance, along with its corresponding index value, is then provided as output through lines 25 and 26.

Notice that the scope of the variable i declared in line 14 is confined to lines 14 18 and is entirely different from the i declared in line 21 with a scope confined to lines 21 27.

Let's pause for a moment and appreciate the advantages of using an array in this program. Even with an attempt to represent and process a much larger array in the source code, the length of the source code would remain unchanged due to our ability to access the array with loops. In fact, we would only need to adjust the number of array elements allocated for the array object to hold in line 11. Consequently, if we need to read in and process 3000 account balances, we just need to change line 11 to the following:

 11:         accountBalances = new decimal [3000]; 

Tip

graphics/bulb.gif

Use the Length property instead of literals or constants to specify the length of an array in the source code. This will allow you to let the program adjust itself whenever you change the size of any array utilized, only requiring a single adjustment in the code. For example


graphics/10infig03.gif


Using Singular or Plural Names for Array Identifiers

graphics/common.gif

Consider the word accountBalances of Listing 10.2. It is clearly in its plural form, as opposed to the singular form accountBalance. The programming community finds it difficult to agree which form is more correct. The proponents of the singular form claim that

 accountBalance[2] 

is preferred, because we refer to just one element, whereas the proponents of the plural form believe that

 accountBalances.Length 

is more suitable because accountBalances represent several account balances.

So even though this book uses the plural form, it is due to my personal preference rather than a general recommendation.



   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net