Mega Code Archive

 
Categories / Delphi / Examples
 

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; 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; 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 ) 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;