Wednesday, November 27, 2024

Auto incrementing elements to Auto extending array

At a recent conference one of the attendees point out to me that my examples of using an auto-extending array only used it as the place for data when I fetched data from a SQL cursor. What about a scenario I want to load values into an auto-extending using a For group or Do loop?

I was surprised that I have not given an example of this scenario. This post remediates that oversight.

I wanted to keep my example program as simple as possible:

01  **free
02  dcl-s Array char(2) dim(*auto : 99) ;
03  dcl-s Counter uns(3) ;

04  for Counter = 1 to 10 ;
05    Array(*next) = %char(Counter) ;
06  endfor ;

07  dsply ('Elements = ' + %char(%elem(Array)) ) ;

08  *inlr = *on ;

Line 2: This is the array definition for the auto-extending array. The array has a maximum of 99 elements.

Line 3: This variable is going to be used to load the array.

Lines 4 – 6: I could not think of any simpler way to load the array than a For group.

Line 4: The For group will be performed 10 times.

Line 5: This is where the value from the variable Counter is loaded into the next element of the array. The array element is *NEXT, for an auto-extending array a new element is added to the array and then the value from Counter is moved into the new element.

Line 7: The Display operation code, DSPLY is used to display the number of elements in the array. The %ELEM BiF returns the number of array elements in the array.

After the program is created and then called this is what is displayed:

DSPLY  Elements = 10

And to really prove that 10 elements were added to the array if I use debug and view the contents of the array at the end of the program I see:

ARRAY(1) = '1 '
ARRAY(2) = '2 '
ARRAY(3) = '3 '
ARRAY(4) = '4 '
ARRAY(5) = '5 '
ARRAY(6) = '6 '
ARRAY(7) = '7 '
ARRAY(8) = '8 '
ARRAY(9) = '9 '
ARRAY(10) = '10'

My oversight is now corrected.

 

This article was written for IBM i 7.5, and should work for some earlier releases too.

2 comments:

  1. One difference between using SQL and loading "by hand" is that if the process is repeated you must manually re-set the %Elem count of the array to zero. SQL appears to do this under the covers.

    ReplyDelete
  2. Actually there *is* an example of a for loop with *next in your previous post, and it's almost the same as this one... but hey, it will make searches easier.
    Thank you for your continuous contributions

    ReplyDelete

To prevent "comment spam" all comments are moderated.
Learn about this website's comments policy here.

Some people have reported that they cannot post a comment using certain computers and browsers. If this is you feel free to use the Contact Form to send me the comment and I will post it for you, please include the title of the post so I know which one to post the comment to.