Sun, May
7 New Articles

Program Flow Using Free Format, Part 2

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

The Do Operations - Free-format RPG IV provides two Do operations: Dow (Do while) and Dou (Do until). For Part One of this article set read here.

Editor's Note: This article is excerpted from chapter 6 of Free-Format RPG IV: Third Edition, by Jim Martin.

Although the fixed form of the Do operation isn’t available in free format, the For operation (covered later in this chapter) contains all the functionality of Do.

Do While

The Dow operation uses a comparison expression, similar to the If operation. The expression is evaluated, and when it is found to be true, program control continues on the next line after the Dow operation. Any number of operations may follow the Dow operation.

The Dow operation has a looping control point at an Enddo operation. (Remember, no generic End operation exists in free format.) At the Enddo, program control is immediately returned to the Dow operation. The comparison expression is then checked again; if it is true, program control continues on the next line following the Dow.

As long as the Dow comparison expression resolves to true, the program continues in a loop. When the expression resolves to false, program control jumps to the first operation after the Enddo that is paired with the Dow operation, ending the loop.

With most Dow groups, a loop-control condition is set just prior to the group and near the end of the group, just before the Enddo operation. Listing 6-4 shows an example of a file read loop that uses Dow.

Program Flow Using Free Format, Part 2 - Figure 1

Listing 6-4: Using Do while (Dow) to read a file until end-of-file

Do Until

Like the If and Dow operations, the Dou operation uses a comparison expression. Dou sets up a future check but otherwise does nothing. Program control flows immediately to the next operation after the Dou. The controlling condition of the loop is usually set soon after the Dou, and an If test is placed afterward to determine whether to continue in the loop. You normally place the Endif for this If just before the Enddo. If the If resolves to true, the program continues after the If, keeps on going after the Endif, and finally comes to the Enddo. At this control point, the Dou condition is tested. If the expression resolves to true, program control resumes at the next operation after the Enddo. If the expression resolves to false, program control “jumps” back (loops back) to the Dou operation.

Listing 6-5 shows an example of a file read loop that uses Dou.

Program Flow Using Free Format, Part 2 - Figure 2

Dow and Dou Differences

The difference between Dow and Dou—and it’s a big one—lies in when the comparison expression is checked, as well as in the program-control action. Program-controlled looping is common, and programmers nearly always adopt one of these operations as their preferred method. In most situations, either approach will provide a satisfactory solution.

If you want to set the controlling condition just once, a do until is the correct form to use. A do while may be the better choice if prior programming statements have already set the controlling condition. Which do loop you choose will depend on many factors, but the biggest factor is probably personal preference.


A For operation and its termination control point, Endfor, define a controlled-loop group of operations. The For group uses an initial specified index value, an increment index value (or default), and a termination value. You can specify the For group indexing to either increment or decrement the current index before checking to see whether the result meets the termination condition.

A For group uses an index variable, as in the following example:

Program Flow Using Free Format, Part 2 - Figure 3

You must define the indexing variable in definition specifications as a numeric field large enough to handle the largest index value. This example specifies no increment, so 1 is used as the default. The loop termination value in the example is 10. If the value of index j is 10 or less, program control will continue to the next operation after the For. At the Endfor, control returns to the For operation, where the index is incremented (or decremented) and then compared with the termination value. If the index is greater than the termination value (if incrementing), program control jumps to the operation immediately after the Endfor operation. If the index is not greater than the termination value, control continues at the next operation after the For operation. The index used in the For group can be used within the group and changed if desired.

A For group can also start with an index value higher than the termination value and decrement until the current index is less than the termination value:

Program Flow Using Free Format, Part 2 - Figure 4

In this example, the index j has an initial value of 100 and a termination value of 1. The index in this case is 2. The first time through the For group, the value of j is 100. The next time through, j equals 98, then 96, and so on until j equals 2. When j equals 2, the For group is again performed. Control then returns to the For statement, where j is decremented by 2, yielding a j value of 0 (zero). Because j’s value is now less than the termination value (1), control passes to the next operation after the Endfor statement.

Listing 6-6 shows some additional examples of For.

Program Flow Using Free Format, Part 2 - Figure 5

Listing 6-6: Using the For operation for controlled looping

Loop Interrupt

The loop operations Dou, Dow, and For normally end when the loop’s index termination requirement is met. There are times in programming when you need to escape from a loop—either all the way out of it or just to its next iteration. RPG IV’s loop interrupt operations Leave and Iter perform these functions for us. (Remember, free-format RPG IV provides no Goto operation.)


The Leave operation causes program control to jump to the next operation after the current Dou, Dow, or For group. The effect is equivalent to a Goto, but it occurs in a structured way. You may be thinking that this operation’s purpose is primarily error handling. Not so. Let’s say you are using a For group to load 10 records from a database into a subfile. However, after five successful record reads, you come to end-of-file. To exit the subfile load routine, you can just set up an “If end-of-file” condition and leave immediately after the Read operation.

The code in Listing 6-6 (above) uses Leave after locating a correct value in a string. Listing 6-7 shows a sample subfile load routine that uses Leave.

Program Flow Using Free Format, Part 2 - Figure 6

Listing 6-7: Using Leave in a load routine to exit at end-of-file


The Iter operation is the other loop interrupt. Specifying Iter causes the program to jump to the current Enddo or Endfor operation (depending on which loop we are in), at which point the normal function of the Enddo or Endfor is performed. As with Leave, the effect is equivalent to a Goto, but, again, the action takes place in a structured way.

A good example of using Iter is what I call “one-at-a-time” error reporting on a data entry panel. If a panel allows entry of 12 different fields, any of which could be entered with invalid data, either we check them one at a time and loop back with one error message or we find all the errors and use a message subfile. To use the first method, just check each field. If the first field is okay, check the second, and so on. If an error occurs at any point, set up for the correct error message, and use Iter to skip all further error checking.

Listing 6-8 illustrates this scenario.

Program Flow Using Free Format, Part 2 - Figure 7

Listing 6-8: Using Iter to skip to the next iteration

The Select Group

The Select operation, with its corresponding operations When, Other, and Endsl, creates a procedural structure very similar to If, Elseif, Else, and Endif.


You code the Select operation on a line by itself, and it starts the select group. Following the Select, you can specify a When operation with a comparison expression. If the expression resolves to false, control is passed to the next When with its comparison expression. The false jumps continue until either an Other statement or the Endsl is reached.

The Other operation is optional. If all When expressions yield false, no action is taken within the Select group unless you have specified an Other operation.

Other means “if none of the above” is true, perform the operations between the Other operation and the Endsl. If any of the When expressions is true, the operations specified between the When that is true and the next When (or Other) are performed, and control then jumps to the Endsl operation. In a Select group with no Other operation, either one set of operations is performed or no operations are performed. If the Select group has an Other operation at the end of the group, at least one set of operations will be performed.

Listing 6-9 shows an example of Select, When, Other, and Endsl.

Program Flow Using Free Format, Part 2 - Figure 8

Listing 6-9: Using Select, When, Other, and Endsl operations

Operations Absent in Free Format

Many RPG programmers are acquainted with the fixed-format Cas (Case) operation and its two-letter suffixes EQ, NE, GT, GE, LT, and LE. These operations are not available in free format, but you can easily replace them by using Select and When operations with Exsr (Perform a subroutine) operations to call the subroutines.

As you have learned, free format also lacks a Goto operation. Doing without a Goto isn’t such a bad thing. Programming style texts and magazine articles have argued nonstop for decades about the good and bad points of using a Goto operation. Rather than anguish over a loss of Goto freedom, let’s look on the bright side: No Goto means no spaghetti code! Many of us have had to sort out programs written by programmers who used Gotos—here, there, and everywhere. It was nothing short of a miracle that the code even worked. Maintaining this kind of code is a programmer’s nightmare.

In earlier versions of RPG, the use of Goto was pretty common. Now, Leave,

Iter, and even LeaveSr (Leave subroutine) let us perform Goto-like functions in a clear and orderly way. Armed with these structured operations, we don’t need a “real” Goto, just an understanding of these loop interrupters. The lack of a Goto operation forces us to think of ways to organize our program logic using structured programming techniques. The end result is programs that are easier to understand and maintain.

More of Jim's Free-Format RPG IV is coming soon in an upcoming issue of MC RPG Developer. Can't wait?  You can pick up Jim Martin's book, Free-Format RPG IV: Third Edition at the MC Press Bookstore Today!


Jim Martin holds a BS degree in mathematics and an MS in computer science. For 26 years, he was employed by IBM, where he wrote RPG applications for customers and worked in the programming laboratory as a programmer on portions of CPF and the OS/400 operating system. After leaving IBM, Jim took post-graduate work in computer science and performed RPG training. He is an IBM-certified RPG IV developer and author of multiple bestselling editions of Free-Format RPG IV, which, since the book's initial publication in 2005, have taught thousands of RPG IV programmers how to be successful with the free-format coding style.

MC Press books written by Jim Martin available now on the MC Press Bookstore.

Free-Format RPG IV: Third Edition Free-Format RPG IV: Third Edition
Improve productivity, readability, and program maintenance with the free-format style of programming in RPG IV.
List Price $59.95

Now On Sale

Free-Format RPG IV: Second Edition Free-Format RPG IV: Second Edition
>Make the transition from coding in fixed-format RPG to free format.
List Price $59.95

Now On Sale

Functions in Free-Format RPG IV Functions in Free-Format RPG IV
Here’s the ultimate guide to writing RPG IV programs with functions in the free-format style.
List Price $59.95

Now On Sale



Support MC Press Online

$0.00 Raised:

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: