Arrays for Intelligent People Part 2

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Knowing how to use arrays is nice, but coming up with creative ways to use them is what it’s all about. This article gives you some examples of different things you can do with arrays.

In the June 1998 issue of Midrange Computing, I introduced arrays in Part 1 of this two-part series. I showed you how to define arrays and gave you some examples of how to manipulate them. I intended to publish Part 2 in July, but one of the nice things about being an editor is that I have discretion over what gets published and when. We’ve had some exciting articles from outside authors lately, and I was eager to let them be published, so I yielded my place to them. However, I don’t want to delay Part 2 any longer. I think it’s time we finished up this discussion.

This month, I concentrate on how to put arrays to work. I include some practical ways to use arrays in typical business applications; I also include some esoteric uses of arrays that you may never need. The point I want to make is that you can do more with arrays than you realize.

Simple Business Techniques Converting Normalized Data to Tabular Form

Database normalization is great for storing data in such a way that you can keep it clean and pull it back out when you need it. However, it’s not the way we look at information.

For instance, suppose a sales manager wants to see how certain items have been selling each month. Figure 1 shows an SQL statement I might use to answer that question. The output I’d get from it is in Figure 2. The information is there, but it’s not pretty, and it wastes paper.

Instead, I prefer a columnar report, like that in Figure 3. But how do I transform Figure 2 into Figure 3? I know a few methods, but my favorite is to use an array. Columnar reports are well-suited to arrays.

A report like this is easy to generate with arrays, as you can see in Figure 4. The ItemTotal and GrandTotal arrays are accumulators, which are printed out when an item

number changes and at end of job, respectively. Using the RPG cycle and output specs makes this sort of program easy to develop. Notice that the arrays are referred to in several places without an index. This technique saves a lot of coding because one operation to an array replaces 13 operations to scalar variables. It may be ugly code (to some people), but I’ll take ugly code and a pretty report over pretty code and an ugly report any day.

Equating Arrays to Scalar Variables in Data Structures

If you work in one of those shops where the cycle and output specs are considered taboo, don’t fret; you can still use arrays. Since DDS doesn’t support array variables (one of its glaring shortcomings, IMHO), you’ll have to equate the scalar variables you define in DDS to the arrays you want to work with.

Figure 5 provides an example. The fields beginning “ItmTot” are scalar fields defined in printer file DDS. Since ItmTot01 is the first subfield in data structure ItemArray, and array ItemTotal overlays ItemArray, ItmTot01 and ItemTotal (1) refer to the same place in memory. Likewise, ItmTot02 and ItemTotal (2) are two names for the same memory address. This means that modifying an array element is equivalent to modifying one of the ItmTot fields defined in the printer file.

Figure 6 shows the RPG III equivalent. Since RPG III variable names can’t be longer than six characters, the printer file fields have been shortened to ITMxx. The principle is the same.

Simulating Multidimensional Arrays

RPG doesn’t support multidimensional arrays. I can safely say that RPG II and RPG III never will. I have asked the good folks at IBM if I can expect multidimensional array support in RPG IV, and they tell me it’s on their list of possible enhancements.

I know a few methods of making 1-D arrays support arrays of two dimensions or more. Since I expect RPG IV to handle multidimensional arrays eventually, and since I know that RPG II and RPG III never will, I’ll use RPG III to illustrate.

The RPG III program in Figure 7 contains a 2-D array called STTB (state table), which consists of 5-byte elements arranged in six rows of five columns. One way to handle this in RPG (and any language that allows only one array dimension) is to define each row as an element of one array and to move a row into another array in which the columns are defined. In Figure 7, STTB is defined as six rows of 25 bytes each. To access the columns, I used the MOVEA (move array) operation to copy one row into array STLN.

Another method I could have used is to convert the 2-D subscript into a 1-D subscript using the following formula:

(row - 1) * number-of-columns + column

Row 1 would contain elements 1 through 5, row 2 would contain elements 6 through 10, and so on. The element at row 4, column 2, would be calculated as (4 - 1) * 5 + 2, or 17.

I could have also defined an array within a multiple occurrence data structure. This method works, but I don’t like it. I have to use one mechanism (the OCCUR op code) to manipulate one dimension, and another mechanism, indexes, to manipulate the other.

The Recondite Stuff

That should give you some idea of the ways in which arrays are typically used in AS/400 shops. As food for thought, I’ll show you some alternative uses of arrays that you are less likely to need.

Table-driven Programming

Table-driven programming means that program logic is stored in data rather than in calculations. Let’s return to Figure 7 for an example.

If you’ve used Client Access, you know that to specify a certain file and member, you use the format lib/file(member). How would you go about writing a routine to extract the library name, file name, and member name from such a string? You could probably do it fairly easily with the SCAN op code (or %scan BIF) and substringing operations. But an easy way to do it is with a Finite State Machine (FSM). (An FSM is a computer program

that has a limited number of defined states, only one of which may be active. How the FSM processes a given input depends on which state is currently active.)

If you’re interested, you can step through the code to see how this works. All I’ll tell you is that the logic of the program is not in calculations but in the state table, STTB. As each character of the input string is processed, the program retrieves a table entry to determine what action to carry out and what the next state of the FSM should be. The same input character can cause different actions to take place (depending on the current state of the FSM), and different characters can force the same action in different circumstances.

If you’re interested in FSMs, read my article, “Extracting Problem Data from PC Files,” in the February 1997 issue of Midrange Computing. I’ve been writing FSMs for years, and I’ve had a lot of fun with them.

Binary Trees

A tree is a hierarchical collection of items. That is, an item can “own” other items, an item can be owned by only one item, and only one item (the “root”) has no owners. If an item can own at most two other items, the tree is called a binary tree.

An array makes a good way to store a binary tree. Any element n in the tree has nodes at elements 2n and 2n + 1.

For example, consider that a person has two parents, and each parent has two parents, and so on, as in Figure 8. Sally’s parents are Fred and Mary, Mary’s parents are Bob and Sarah, and Fred’s parents are Bill and Betty. Figure 9 shows how this information would be stored in an array. If we make a rule that person n’s father is to be stored in element 2n and n’s mother is stored in element 2n + 1, we can deduce that Mary’s father and mother are in elements (2 * 3) and (2 * 3 + 1); that is, elements 6 and 7, respectively.

Use Your Imagination!

This is not an exhaustive list; you can do a lot more with arrays. But maybe this article will help you think of ways you can more effectively use arrays in your programs. Get those creative juices flowing, and put arrays to work solving problems in your shop.


ILE RPG for AS/400 Reference Version 4 (SC09-2508, CD-ROM QB3AGZ00) RPG/400 Reference (SC09-1817, CD-ROM QBKAQV00)

select item, xmonth, sum(qty*price)

from slsxacts

group by item,xmonth

Figure 1: This SQL statement generates the report in Figure 2


A1 1 14.00 A1 2 6.00 A1 3 2.00 A2 2 6.00 A2 4 6.00

Figure 2: Relational tools typically yield reports that are accurate but ugly

Item Jan Feb Mar Apr May ... Dec Total

A1 14.00 6.00 2.00 ... 22.00 A2 6.00 6.00 ... 12.00 Total 14.00 12.00 2.00 6.00 .00 ... .00 34.00

Figure 3: This report is easier to read than the one in Figure 2

FSlsSumPF ip e k disk

FQSysPrt o f 132 printer oflind(*inOF)

D ItemTotal s +1 dim(13) like(Amt)

D GrandTotal s +1 dim(13) like(Amt)

D MonthNames s 9 dim(13) perrcd(7) ctdata

ISlsSumR 01

I Item L1

C L1 eval ItemTotal = *zero


C eval ItemTotal (Month) =

C ItemTotal (Month) + Amt


CL1 xfoot ItemTotal ItemTotal (13)

CL1 eval GrandTotal =

C GrandTotal + ItemTotal

OQSysPrt H 1P 2 04

O or OF

O ‘Item’

O MonthNames + 1

O T L1 1

O Item

O 5 ‘ ‘

O ItemTotal 4 + 1

O T LR 1

O ‘Total’

O GrandTotal 3 + 1

**ctdata MonthNames

Jan Feb Mar Apr May Jun Jul

Aug Sep Oct Nov Dec Total

D ItemArray ds

D ItmTot01 6 2

D ItmTot02 like(ItmTot01)

... (ItmTot03 through ITM12 are defined similarly)

D ItmTot13 like(ItmTot01)

D ItemTotal dim(13) like(ItmTot01) inz(*zero)

D overlay(ItemArray)

E IT 13 6 2


I 1 62ITM01

I 7 122ITM02

... (ITM03 through ITM12 are defined similarly)

I 73 782ITM13

I 1 782IT

Figure 4: This short program is quickly developed and easily produces a columnar report

Figure 5: RPG IV code using a data structure to equate an array and printer file fields

Figure 6: The RPG III equivalent of Figure 5

* Break a string of the format lib/file(member) into components


E INP 34 1 Input from caller

E VAL 34 1 Work variable

E CH 5 5 1 Character types

E STTB 1 6 25 State table

E STLN 5 5 State table line










C EXSR INIT Initialize








C GETENT BEGSR Get table entry


C Z-ADD1 CX 30





























C Z-ADD1 ST 30


C MOVEL’*LIBL’ LIB P Default value


C MOVEL’*FIRST’ MEMBER P Default value








** CH



Er00 Er00 Er00 Er00 SC02

FI00 FI05 Er00 LI03 SC02

Er00 Er00 Er00 Er00 SC04

FI00 FI05 Er00 Er00 SC04

Er00 Er00 Er00 Er00 SC06

Er00 Er00 ME00 Er00 SC06

Figure 7: Simulating a 2-D array


Fred Mary

Bill Betty Bob Sarah

Figure 8: A binary tree of a person’s lineage

Sally Fred Mary Bill Betty Bob Sarah

Figure 9: A binary tree stored as an array

Ted Holt

Ted Holt is IT manager of Manufacturing Systems Development for Day-Brite Capri Omega, a manufacturer of lighting fixtures in Tupelo, Mississippi. He has worked in the information processing industry since 1981 and is the author or co-author of seven books. 

MC Press books written by Ted Holt available now on the MC Press Bookstore.

Complete CL: Fifth Edition Complete CL: Fifth Edition
Become a CL guru and fully leverage the abilities of your system.
List Price $79.95

Now On Sale

Complete CL: Sixth Edition Complete CL: Sixth Edition
Now fully updated! Get the master guide to Control Language programming.
List Price $79.95

Now On Sale

IBM i5/iSeries Primer IBM i5/iSeries Primer
Check out the ultimate resource and “must-have” guide for every professional working with the i5/iSeries.
List Price $99.95

Now On Sale

Qshell for iSeries Qshell for iSeries
Check out this Unix-style shell and utilities command interface for OS/400.
List Price $79.95

Now On Sale



Support MC Press Online





  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things

    Read Node.js for Enterprise IBM i Modernization Now!


  • Profound Logic Solution Guide

    SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation.
    Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects.
    The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the companyare not aligned with the current IT environment.

    Get your copy of this important guide today!


  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.


  • Progressive Web Apps: Create a Universal Experience Across All Devices

    LANSAProgressive Web Apps allow you to reach anyone, anywhere, and on any device with a single unified codebase. This means that your applications—regardless of browser, device, or platform—instantly become more reliable and consistent. They are the present and future of application development, and more and more businesses are catching on.
    Download this whitepaper and learn:

    • How PWAs support fast application development and streamline DevOps
    • How to give your business a competitive edge using PWAs
    • What makes progressive web apps so versatile, both online and offline



  • The Power of Coding in a Low-Code Solution

    LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed.
    Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Why Migrate When You Can Modernize?

    LANSABusiness users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.


  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact


  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using as a pre-built development environment



  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.



  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.



  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails


  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.



  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed.
    Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Node Webinar Series Pt. 1: The World of Node.js on IBM i

    SB Profound WC GenericHave you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.
    Part 1 will teach you what Node.js is, why it's a great option for IBM i shops, and how to take advantage of the ecosystem surrounding Node.
    In addition to background information, our Director of Product Development Scott Klement will demonstrate applications that take advantage of the Node Package Manager (npm).
    Watch Now.

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY the one package that solves all your document design and printing challenges on all your platforms.

    Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. How can you be sure you won’t miss important system events?
    Automate your message center with the Robot Message Management Solution. Key features include:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing.
    Manage your reports with the Robot Report Management Solution. Key features include:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.