Skip to content
Daniel Long edited this page Sep 29, 2026 · 2 revisions

Arrays

Arrays in RPG are 1-based (the first element is index 1).

// Fixed-size array
DCL-S names VARCHAR(50) DIM(5);
names(1) = 'Alice';
names(2) = 'Bob';
DSPLY names(1);  // Alice

// Variable-size array
DCL-S items VARCHAR(50) DIM(*VAR: 100);
%ELEM(items) = 3;
items(1) = 'First';

// Array initialization
DCL-S scores INT(10) DIM(3) INZ(0);

Array Operations

DCL-S names VARCHAR(20) DIM(5);
DCL-S idx INT(10);

names(1) = 'Charlie';
names(2) = 'Alice';
names(3) = 'Bob';

SORTA names;  // Sort ascending

idx = %LOOKUP('Bob' : names);
DSPLY %CHAR(idx);  // Position of 'Bob' after sort

// FOR-EACH loop
FOR-EACH name IN names;
  IF name <> '';
    DSPLY name;
  ENDIF;
ENDFOR;

Searching an Array: %LOOKUP

%LOOKUP(value : array {: start {: count}}) returns the index of the first element equal to value, or 0. start and count limit the search.

%LOOKUPLT, %LOOKUPLE, %LOOKUPGT and %LOOKUPGE find the element nearest the value: the greatest element below it (LT), the least above it (GT), or an equal element if there is one (LE, GE). They rely on the array's order, so the array must be declared ASCEND or DESCEND (IBM: RNF0592):

DCL-S limits INT(10) DIM(5) ASCEND;   // 10, 20, 30, 40, 50
idx = %LOOKUPLT(25 : limits);         // 2: 20 is the nearest below 25
idx = %LOOKUPGE(25 : limits);         // 3: 30 is the nearest at or above

Compile-Time Data (CTDATA)

An array declared CTDATA takes its values from compile-time data at the end of the source, after the program's last line. A section starts with **CTDATA name in position 1; each record holds PERRCD(n) elements (one if PERRCD is left out), each as wide as the element. A number is written as its digits, with the decimal point implied by the declaration:

**FREE
DCL-S months CHAR(3) DIM(12) CTDATA PERRCD(6);
DCL-S rates PACKED(5:2) DIM(3) CTDATA;

DSPLY months(2);          // FEB
DSPLY %CHAR(rates(1));    // 1.25
*INLR = *ON;
**CTDATA months
JANFEBMARAPRMAYJUN
JULAUGSEPOCTNOVDEC
**CTDATA rates
00125
01000
99999

In fixed format a section may also start with just **; unnamed sections load the CTDATA arrays in the order they are declared.

Tables and %TLOOKUP

A table is an array whose name begins with TAB. It is filled from compile-time data and searched with %TLOOKUP(value : table), which returns *ON when an element matches. A table is never indexed (IBM: RNF0752), and %TLOOKUP accepts only a table (RNF0597); use %LOOKUP for any other array. %TLOOKUPLT, LE, GT and GE need the table in ASCEND or DESCEND order (RNF0507).

DCL-S tabCodes CHAR(3) DIM(4) ASCEND CTDATA;

IF %TLOOKUP('LAX' : tabCodes);
  DSPLY 'LAX is a known code';
ENDIF;
*INLR = *ON;
**CTDATA tabCodes
DFW
LAX
NYC
ORD

Clone this wiki locally