%SUBARR

23 Views


In RPGLE (IBM i), %SUBARR is a built-in function (BIF) used to work with part of an array — basically a slice of an array.


🔍 What %SUBARR Does

%SUBARR returns a subset (portion) of an array, starting at a given element, and optionally for a given number of elements.


📘 Syntax

%SUBARR(array : start-index : number-of-elements)
  • array → The array you want to slice.

  • start-index → The starting element (1-based index).

  • number-of-elements → (Optional) How many elements to include. If omitted, it takes everything from start-index to the end of the array.


Examples

1. Copying part of an array

dcl-s Arr1 char(10) dim(5) inz(%array('A':'B':'C':'D':'E'));
dcl-s Arr2 char(10) dim(2);

Arr2 = %subarr(Arr1 : 2 : 2);  // Arr2 = { 'B' , 'C' }

2. Processing a subarray in a loop

dcl-s numbers int(5) dim(6) inz(%array(10:20:30:40:50:60));

for-each value in %subarr(numbers : 3 : 2);
   dsply value;   // Will display 30 and 40
endfor;

3. Assigning values into part of an array

dcl-s base int(10) dim(5) inz(*zeros);

%subarr(base : 2 : 3) = %array(100:200:300);

// base = [0,100,200,300,0]

⚠️ Notes

  • Index is 1-based (not 0-based like C or Java).

  • If the subarray length goes beyond the array’s dimension, you’ll get a runtime error.

  • Often used with %LOOKUP, %XFOOT, or %ELEM for advanced array handling.


Summary:
%SUBARR lets you take a slice of an array (like arrays in Python, Java, or C#). It’s useful for assignments, looping over partial data, or manipulating chunks of arrays.


 

Post Comments