Adjusting for the Zero-Based Array Index


The index of any array commences at 0; this cannot be altered. Occasionally, however, you might want a program to give the user the impression that a different and more suitable numbering scheme is being applied to a collection of data items. For example, it might often be more convenient to think of the first item in a collection as having index 1, rather than index 0. By making appropriate adjustments in the source code, you can accomplish this objective.

As an example, let's adjust Listing 10.2 to give the user the impression that the first account balance is number 1 (instead of 0) and the last number is 5 (instead of 4). First, we need to locate all lines of code that prints the index (the variable i in this case) onscreen lines 16 and 23 in this case. Then we need to add 1 to the value of i, turning 0 into 1 and 4 into 5:

 16:             Console.Write("Enter balance with index { 0} : ", (i + 1)); 25:             Console.WriteLine("Account balance with index { 0} : { 1:C} ", 26:                 (i + 1), accountBalances[i]); 

The first couple of lines of output from the altered program will now look like

 Please enter five account balances: Enter balance with index 1: 

In case we entered the same values as in the sample output of Listing 10.2, the first couple of sample output lines providing the account balances after adding interest would look like the following:

 Account balance with index 1: $11,000.00 Account balance with index 2: $22,000.00 ... 

providing the index number 1 instead of 0, 2 instead of 1 and so on.

Instead of receiving an index as output, the reader must sometimes provide a number as input representing an index to, for example, access the information contained in a corresponding array element. This number will also have to be adjusted before it can be used to access the corresponding array element inside the program. In our case, the program would have to subtract 1 from the number entered by the user, as shown in the following lines of code, that can be inserted after line 27 of Listing 10.2. The code allows the user to access one of the balances indexed 0 to 4 by entering a number between 1 and 5.

 int myIndex; Console.Write("Enter number of account to get balance: "); myIndex = Convert.ToInt32(Console.ReadLine()) - 1; Console.WriteLine("Balance of account balance number: { 0}  is: { 1} ",       myIndex + 1, accountBalances[myIndex]); 


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

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: