29
Fri, Nov
0 New Articles

Arrays for Intelligent People Part 2

RPG
Typography
  • 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.

References:

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

ITEM XMONTH SUM ( QTY * PRICE )

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

C eval ItemTotal (Month) =

C ItemTotal (Month) + Amt

C

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 IDS

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

ITBLENT DS

I 1 2 ACTION

I 3 40NEXTST

C *ENTRY PLIST

C PARM INPUT 34

C PARM LIB 10

C PARM FILE 10

C PARM MEMBER 10

C*

C EXSR INIT Initialize

C ST DOUEQ*ZERO

C EXSR GETENT

C EXSR DOACT

C Z-ADDNEXTST ST

C ENDDO

C RETRN

C***********

C GETENT BEGSR Get table entry

C ADD 1 IX

C Z-ADD1 CX 30

C INP,IX LOKUPCH,CX 33

C *IN33 IFEQ *OFF

C Z-ADD5 CX

C ENDIF

C MOVEASTTB,ST STLN

C MOVEASTLN,CX TBLENT

C ENDSR

C***********

C DOACT BEGSR

C SELEC

C ACTION WHEQ ‘SC’

C ADD 1 VX

C MOVE INP,IX VAL,VX

C ACTION WHEQ ‘LI’

C MOVEAVAL LIB

C EXSR CLRVAL

C ACTION WHEQ ‘FI’

C MOVEAVAL FILE

C EXSR CLRVAL

C ACTION WHEQ ‘ME’

C MOVEAVAL MEMBER

C EXSR CLRVAL

C ENDSL

C ENDSR

C***********

C INIT BEGSR

C MOVEAINPUT INP

C MOVE *ZERO IX 30

C Z-ADD1 ST 30

C EXSR CLRVAL

C MOVEL’*LIBL’ LIB P Default value

C MOVEL*BLANKS FILE

C MOVEL’*FIRST’ MEMBER P Default value

C ENDSR

C***********

C CLRVAL BEGSR Clear VAL

C MOVE *BLANKS VAL

C MOVE *ZERO VX 30

C ENDSR

C*

** CH

()/A

** STTB

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

Sally

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

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 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. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • 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 company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY 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. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) 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:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. 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:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot 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:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business 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.

  • 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:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic 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.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? 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: