Wednesday, March 2, 2011

How to find the starting and the ending element positions of an array

If you're often having to change array sizes and/or starting indexes, you may also have to make changes in multiple locations inside the program. Let's take a look at following arrays for example:

 
var
  a1 : array [ 0 ..  5] of integer;
  a2 : array [10 .. 60] of integer;
Listing #1 : Delphi code. Download arrays (0.18 KB).
 
One way to go through all array items is to hard code the starting and ending indexes of the array:
 
  for i := 10 to 60 do
  begin
    //
    // your code goes here...
    // a2[ i ]
    //
  end;
Listing #2 : Delphi code. Download arrays2 (0.21 KB).
 
On the other hand, you can use "Low()" and "High()" functions to find the starting and the ending element positions of an array.
 
  //
  // following function call
  // will return 10 (starting index)
  // because a2 was defined as:
  //   a2 : array [10 .. 60] of integer;
  //
  Low( a2 )

  //
  // following function call
  // will return 5 (ending index)
  // because a1 was defined as:
  //   a1 : array [ 0 ..  5] of integer;
  //
  High( a1 )
Listing #3 : Delphi code. Download arrays3 (0.29 KB).
 
This could come in handy when you have to iterate through a list of items in an array without hard coding the size of the array. For example:
 
  for i := Low( a2 ) to High( a2 ) do
  begin
    //
    // your code goes here...
    // a2[ i ]
    //
  end;
Listing #4 : Delphi code. Download arrays4 (0.22 KB).

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Kang Iwan K-sev | Thank's for your visit To My Site - Ridwan Mulyana | Cibeureum