ILERPG.com β€” IBM i Β· ILE RPG Β· AS400 Mastery
2 min readΒ· Admin

Arrays in ILE RPG: Declare, Load, Search, Sort

Six region codes become six variables, then eight, then a chain of IF statements nobody wants to maintain. An array collects the whole list under one name, indexed by position, so the same few lines of code keep working however many entries the list holds.

DIM and %ELEM

DIM(n) reserves n elements. %ELEM(array) returns that count from the declaration, so loop bounds and capacity checks never depend on a hard-coded number that someone has to remember to change.

Compile-time arrays

CTDATA and PERRCD, with a named **CTDATA section at the end of the source, bake a small, static list into the compiled program. That is appropriate for a closed list that changes only with a release, and inappropriate for anything the business maintains independently β€” which belongs in a table.

Loading safely

Writing past the declared element count is a runtime array-index error. A validation file that grows beyond the array's size, with no guard in place, ends the program. Check the running count against %ELEM before every assignment.

Exact and ranged searches

%LOOKUP performs an exact-match scan and returns the position or zero. Passing the loaded count as the fourth argument limits the search to real data. The ranged lookups β€” %LOOKUPLT, %LOOKUPLE, %LOOKUPGT, and %LOOKUPGE β€” find the closest qualifying element on an array declared ASCEND or DESCEND, which is how pricing tiers and scheduling windows are resolved.

SORTA on a partly loaded array

SORTA sorts in the direction the declaration specifies. On an array that is only partly filled, sort just the loaded elements. Sorting the whole array moves the unused default values to the front and pushes real values out of the range being searched.

sorta %subarr(pickupDate : 1 : pickupCount);
matchIndex = %lookupge(requestedDate : pickupDate : 1 : pickupCount);

Lesson 20 closes with a dock-scheduling routine that loads, sorts, and searches an array of dates β€” and sets up Lesson 21's answer to the weaknesses of parallel arrays.

Get the lesson

Lesson 20, β€œArrays: Declaration, Loading, and Lookup,” is part of Beginner ILE RPG in IBM i ILE RPG Mastery and is available at ILERPG.com for USD 10. The complete Beginner ILE RPG series β€” all 18 lessons β€” is USD 180, or USD 135 with coupon code RPG30, which takes 25% off when you purchase the full series.