0% found this document useful (0 votes)
22 views

RPG IV Programming Fundamentals Workshop for IBM i Student Notebook (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

RPG IV Programming Fundamentals Workshop for IBM i Student Notebook (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 418

V10.

cover

IBM Training Front cover


Student Notebook

RPG IV Programming Fundamentals Workshop for IBM i


Course code AS06 ERC 8.1

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Trademarks
IBM® is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United States,
or other countries, or both:
AS/400® AS/400e™ DB™
DB2® Integrated Language Iterations®
Environment®
i5/OS™ Language Environment® OS/400®
PartnerWorld® Power Systems™ Power Systems Software™
Power® Rational® Redbooks®
RPG/400® System i® Worklight®
400®
Adobe is either a registered trademark or a trademark of Adobe Systems Incorporated in the United
States, and/or other countries.
Pentium is a trademark or registered trademark of Intel Corporation or its subsidiaries in the United
States and other countries.
Windows is a trademark of Microsoft Corporation in the United States, other countries, or both.
Java™ and all Java-based trademarks and logos are trademarks or registered trademarks of
Oracle and/or its affiliates.
VMware and the VMware “boxes” logo and design, Virtual SMP and VMotion are registered
trademarks or trademarks (the “Marks”) of VMware, Inc. in the United States and/or other
jurisdictions.
Other product and service names might be trademarks of IBM or other companies.

March 2019 edition


The information contained in this document has not been submitted to any formal IBM test and is distributed on an “as is” basis without
any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer
responsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. While
each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will
result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.

© Copyright International Business Machines Corporation 2002, 2019.


This document may not be reproduced in whole or in part without the prior written permission of IBM.
US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

TOC Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

Course description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Unit 1. RPG IV introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
RPG IV's legacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
What is RPG IV? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Application development tools: Packaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Development cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Describing a programming solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10
RPG IV terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
RPG IV specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
Print program: RPG code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
Print program: Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
Create RPG IV program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
IBM i source physical file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17
The process of creating an RPG IV program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
CRTBNDRPG compile options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20
Compiler listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22
Compiler directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23
Machine exercise: Coding and compiling RPG IV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
Checkpoint (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-28
Checkpoint (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-29
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30

Unit 2. Coding specifications for RPG IV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Source specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Symbolic names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Field naming rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
RPG IV indicators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Machine exercise: Sequencing RPG IV specifications and compiling . . . . . . . . . . . . . . . . . 2-8
Control specification (H) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Control specification keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
File specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
File specification components (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
File specification components (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15
Device type and processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
Database processing options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
Control and file specifications: Employee print program . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18
Definition specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
Definition specifications to define data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21
Defining a data structure and array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-23
Where are externally described descriptions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25
Input specification for input data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-26

© Copyright IBM Corp. 2002, 2019 Contents iii


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Calculation specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-27


Calculation specification structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-28
Typical calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-29
Common opcodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-30
Rules of coding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-31
Output specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-33
Class exercise: Coding a simple listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-34
Machine exercise: Coding a report program and adding overflow . . . . . . . . . . . . . . . . . . .2-35
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-36
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-37

Unit 3. Data representation and definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2
RPG IV data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-3
Character data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-4
Numeric data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-6
Zoned decimal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-7
Packed decimal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-8
Integer/Unsigned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-10
Named indicators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-12
Date, Time, and TimeStamp fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-13
What can be done? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-15
Date formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-16
Time formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-18
Moving data to and from date, time, and timestamp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-19
Other data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-20
Figurative constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-21
Data definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-22
Externally described files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-23
Defining externally described data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-24
Overriding externally defined data names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-25
LIKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-27
Machine exercise: Data definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-28
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-29
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-30

Unit 4. Manipulating data in calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2
Types of expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-3
Assignment opcodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-4
Assignment of a numeric variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-6
Assignment of a character variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-7
Arithmetic operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-8
Arithmetic opcodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-9
Addition and subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-11
Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-12
Numeric overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-13
Division and remainders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-15
Coding BiFs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-17
Exponentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-18
Machine exercise: Adding arithmetic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-19

iv RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

TOC Comparison operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20


Class exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-22
If/Else/EndIf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-23
If expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24
Using Do While (DoW) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-25
String handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-26
String handling BiFs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-27
Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-28
Remove characters: %Trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29
Length and size of a string: %Len and %Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-30
Scan for character string: %Scan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-31
Scan and replace for character string: %ScanRpl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-32
Extract substring: %Subst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-34
Replace string of characters: %Replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-35
Convert to character: %Char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-36
Edit with %EditC or %EditW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37
Convert to numeric: %Int and %Dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39
Convert string: %Xlate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-40
Date/Time/TimeStamps: Testing for valid dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-41
Moving to and from date and time fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42
Date and time durations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-44
Duration considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-45
Precedence rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-47
Precedence rules: Using parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-48
Precision: Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-49
Specifying precision rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-51
Machine exercise: Data manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-52
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-53
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-54

Unit 5. Using printer and display files in an RPG IV program . . . . . . . . . . . . . . . . . . . . . . . . 5-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Printing process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Printing elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Elements that control printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Which OUTQ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Using a printer file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
Printer file characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12
Printer file DDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
Printer DDS keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14
PRTF DDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
Output report: Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17
PRTF: DDS example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18
PRTF RPG IV program: Itemlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20
Edit codes for printed output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-23
Display file descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-24
Display record format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-25
Display design (1 of 5) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-26
Display design (2 of 5) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-27
Display design (3 of 5) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-28

© Copyright IBM Corp. 2002, 2019 Contents v


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Display design (4 of 5) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-29


Display design (5 of 5) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-30
Display attribute (DSPATR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-32
DSPATR and color displays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-33
Enabling function keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-34
Function keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-35
Field-level keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-36
Validity checking keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-37
DDS message keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-38
Message coding examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-40
Creating and using screen formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-41
RPG screen operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-42
Inquiry example: Item inquiry program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-43
Machine exercise: Coding an inquiry program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-45
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-46
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-47

Unit 6. Structured programming, error handling, subprocedures, and subroutines . . . . . .6-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-2
Introducing structured programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-3
If operation code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-4
If and Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-5
Make your expressions clear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-6
'AND' or 'OR' in expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-7
Nested structured groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-8
Nested If/Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-9
Select/When/Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-10
If versus Select group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-11
Do While (DOW) and Do Until (DOU) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-12
For/EndFor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-14
Program problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-15
Exceptions and methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-16
Methods of managing exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-18
IBM i logic flow for error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-20
Using the (E) extender . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-22
E-extender, %Error, and %Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-23
Program status data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-25
Examples of program status codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-27
What else is in the program status data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-28
Error handling recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-29
Calls in RPG IV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-30
Calling another program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-31
The calling program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-32
The called program: Return to caller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-33
Advantages of prototyping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-34
Options keyword for parameter definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-35
Setting *INLR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-37
What is a subprocedure? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-38
Writing code for subprocedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-40
Different types of RPG IV source members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-42
Major features of subprocedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-44

vi RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

TOC What are local variables? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-45


Basic subprocedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-46
Invoking the subprocedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-48
Procedure specs and the procedure interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-49
Returning the result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-51
Defining the prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-52
Subprocedures calling other subprocedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-53
Machine exercise: Coding procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-54
Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-55
Coding subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-56
Execution of a subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-58
Implicit execution of a subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-59
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-60
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-61

Unit 7. Using arrays, data structures, and data areas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
What is an array? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Processing data in an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Summary of Definition spec keywords for arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5
Compile time load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Naming arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8
Moving array data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
Crossfooting arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Using arrays in a loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11
%LookUpxx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12
%LookUpxx example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-13
SortA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15
BiFs and arrays: %Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16
BiFs and arrays: %Elem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17
BiFs and arrays: %SubArr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18
Characteristics of data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-19
Types of data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20
Defining data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
Externally described data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-23
Uses for data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-25
Qualified names and templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-26
Qualified Template and LikeDS: Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-27
Compound data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28
LikeRec keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-29
Arrays within data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-30
Array data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-31
Array as a component of a data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32
Multidimensional array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33
Reinitializing data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-34
What is a data area? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-35
Uses for a data area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-36
Comparison of data area types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-37
Explicitly process a data area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-38
Naming a data area using a variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-40
Implicitly process a data area (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-41

© Copyright IBM Corp. 2002, 2019 Contents vii


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Implicitly process a data area (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-42


Local data area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-43
LDA definition, In and Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-44
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-45
Machine exercise: Data structures and data areas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-46
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-47

Unit 8. Accessing the DB2 database using RPG IV. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-2
DB file: Physical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-3
DB file: Logical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-4
DB file descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-6
DDS limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-8
Physical file DDS keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-9
Logical file DDS keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-10
DDS field reference file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-11
DDS: PF/LF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-12
Creating DB files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-13
Helpful commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-14
File operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-16
File-related BiFs and extenders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-18
File open and close: Explicit or implicit? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-20
Explicit open and close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-21
Open data path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-22
Data can be accessed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-23
Sequential processing: Read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-24
Sequential processing: Read example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-25
Sequential processing: Record addition with Write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-26
Position file cursor with SetLL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-27
Position file cursor with SetLL: Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-28
Random processing: Chain by key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-30
Random processing with Chain by record key: Example . . . . . . . . . . . . . . . . . . . . . . . . . .8-31
Random processing composite key (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-32
Random processing composite key (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-33
Random processing with Chain by RRN: Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-34
Sequential processing: ReadP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-35
Sequential processing: ReadE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-36
Sequential processing: ReadE example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-37
Positioning file cursor: SetGT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-38
ReadP and SetGT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-39
ReadPE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-40
Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-41
Database record locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-42
Record locking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-43
Read update file without locking record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-44
Releasing a locked record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-45
Considerations when releasing locked record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-46
Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-47
Deleted records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-48
INFDS: File information data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-49
Subset of file status codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-51

viii RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

TOC Handling a duplicate key on write to file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-52


Using SQL in an RPG IV program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-54
Why use SQL in an RPG IV program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-55
Machine exercise: Maintaining database files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-56
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-57
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-58

Unit 9. What’s next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
What have you learned? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
To do list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Topics list for next course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5
Useful references and websites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7

Appendix A. RPG IV style guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1

Appendix B. Checkpoint solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-1

Bibliography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .X-1

© Copyright IBM Corp. 2002, 2019 Contents ix


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

x RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

TMK
Trademarks
The reader should recognize that the following terms, which appear in the content of this training
document, are official trademarks of IBM or other companies:
IBM® is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United States,
or other countries, or both:
AS/400® AS/400e™ DB™
DB2® Integrated Language Iterations®
Environment®
i5/OS™ Language Environment® OS/400®
PartnerWorld® Power Systems™ Power Systems Software™
Power® Rational® Redbooks®
RPG/400® System i® Worklight®
400®
Adobe is either a registered trademark or a trademark of Adobe Systems Incorporated in the United
States, and/or other countries.
Pentium is a trademark or registered trademark of Intel Corporation or its subsidiaries in the United
States and other countries.
Windows is a trademark of Microsoft Corporation in the United States, other countries, or both.
Java™ and all Java-based trademarks and logos are trademarks or registered trademarks of
Oracle and/or its affiliates.
VMware and the VMware “boxes” logo and design, Virtual SMP and VMotion are registered
trademarks or trademarks (the “Marks”) of VMware, Inc. in the United States and/or other
jurisdictions.
Other product and service names might be trademarks of IBM or other companies.

© Copyright IBM Corp. 2002, 2019 Trademarks xi


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

xii RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

pref
Course description
RPG IV Programming Fundamentals Workshop for IBM i

Duration: 4 days

Purpose
This course teaches the basics of the IBM i RPG IV programming language.
It is the first of two courses that should be attended in sequence.
This course is a comprehensive exposure to the basic features and functions
of RPG IV for Version 7. It does not introduce either information processing
or programming in general. Students who are new to programming should
attend other courses that are offered by local technical colleges or self-study
methods.
This course is designed to enable a trained programmer to develop and
maintain simple RPG IV programs written using the latest features and
techniques available in the Version 7 compiler.

Audience
This course is the first in a series of two courses designed for programmers
who are new to RPG IV. Basic programming experience is required. The
student should have attended at least an introductory course to programming
such as one of those available at technical colleges. The student is not
taught the concepts of programming.
Experienced programmers who are new to the Power System with IBM i
should also attend this course. Examples of other programming languages
are BASIC, COBOL, or RPG II.
This course is not designed for RPG III programmers who want to learn RPG
IV. The Moving from RPG/400 to System i RPG IV course (OE85/OE850) is
designed to satisfy this need, when it is available in your geography. This
course is too basic for experienced RPG III programmers.
If OE85/OE850 is not offered in your geography, you should attend this
course instead.
Notes:
The term RPG/400 refers to both System/38 RPG as well as IBM i
(AS/400) RPG/400 (also known as RPG III).
This course focuses entirely on the features of the RPG IV Version 7
compiler and the techniques that this compiler provides. Features of V7
are discussed.

© Copyright IBM Corp. 2002, 2019 Course description xiii


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Previous techniques and the maintenance of programs that are written using
legacy techniques, such as fixed format calculations, are not covered in the
classroom. Some additional material and the bibliography will assist the new
RPG IV programmer in the maintenance of legacy applications.

Prerequisites
Before attending this course, the students should be able to:
• Use a Windows-based PC
• Run PC applications using menus, icons, toolbars, and so forth
• Write a simple program in another high-level language (for example, CL,
COBOL, BASIC, or RPG II)
• Use basic IBM i tools, including:
- CL commands
- Online Help
- WRKSPLF and related commands to manage output
- WRKJOB, DSPMSG, DSPJOB commands and so forth to perform basic
problem determination
• Use and display IBM i print queues
• Use the RSE/LPEX Editor to create and maintain DDS
• Create and maintain physical and logical files
Students must have attended these courses:
• Introduction to IBM i for New Users (OE98/OE980)
• System i Application Programming Facilities Workshop (OL49/OL490)
Attendance at IBM i RPG Development with Rational Developer for Power
Systems Software V8 (RN500) is strongly recommended. Experience with
Printer and Display files prior to attending this course is beneficial as well.

xiv RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

pref Objectives
After completing this course, you should be able to:
• Write RPG IV version 7.1 programs to produce reports
• Write simple RPG IV version 7.1 inquiry programs that interact with
displays
• Review compilation listing, find and correct compilation errors
• Maintain existing applications written in the RPG IV Version 7.1 language
• Use many popular RPG IV built-in functions

Contents
1. RPG IV introduction
2. Coding specifications for RPG IV
3. Data representation and definition
4. Manipulating data in calculations
5. Using printer and display files in an RPG IV program
6. Structured programming, error handling, subprocedures, and subroutines
7. Using arrays, data structures, and data areas
8. Accessing the DB2 database using RPG IV
9. What's next?

Curriculum relationship
This course is the first of two courses designed to develop new RPG IV
programmers. It is part of the IBM i programming curriculum to support the
RPG IV Version 7 compiler. Below is the other one that you should attend to
enhance your skills in developing applications using the RPG IV language
after you have completed this course. Please contact your local IBM
Education Center regarding the availability of these classes in your area:
• AS10/AS100 RPG IV Advanced Programming Workshop for IBM i

© Copyright IBM Corp. 2002, 2019 Course description xv


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

xvi RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

pref
Agenda
Day 1
Welcome and administration
Unit 1: RPG IV introduction
Lab 1: Coding and compiling RPG IV
Unit 2: Coding specifications for RPG IV
Lab 2: Sequencing RPG IV specifications and compiling
Lab 3: Coding a report program

Day 2
Lab 4: Adding overflow
Unit 3: Data representation and definition
Lab 5: Data definition
Unit 4: Manipulating data in calculations
Lab 6: Adding arithmetic function
Lab 7: Data manipulation

Day 3
Unit 5: Using printer and display files in an RPG IV program
Lab 8: Coding an inquiry program
Unit 6: Structured programming, error handling, subprocedures, and
subroutines
Lab 9: Procedures
Unit 7: Using arrays, data structures, and data areas

Day 4
Unit 7: Using arrays, data structures, and data areas (continued)
Lab 10: Data structures and data areas
Unit 8: Accessing the DB2 database using RPG IV
Lab 11: Maintaining database files
Unit 9: What’s next?

© Copyright IBM Corp. 2002, 2019 Agenda xvii


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

xviii RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 1. RPG IV introduction

What this unit is about


This unit introduces RPG IV programming terms and concepts. It overviews
RPG IV and the basics of the language. It also discusses the steps involved
when coding RPG IV programs. A sample program is presented in this unit.

What you should be able to do


After completing this unit, you should be able to:
• Explain the general purpose of each RPG IV specification type
• Describe the steps to code and test an RPG IV program
• List several unique features of the RPG language and discuss RPG's
strengths and weaknesses
• Browse an RPG IV compiler listing

How you will check your progress


• Checkpoint questions
• Machine exercise
• Given a simple RPG IV program, the class enters the source member
using either the RSE/LPEX or SEU editor and compiles the program. The
students are exposed to the editor and a compilation listing.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:


• Explain the general purpose of each RPG IV specification type
• Describe the steps to code and test an RPG IV program
• List several unique features of the RPG language and discuss
RPG's strengths and weaknesses
• Browse an RPG IV compiler listing

© Copyright IBM Corporation 2002, 2014

Figure 1-1. Unit objectives AS068.1

Notes:

1-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

RPG IV's legacy


IBM i

• Most popular high-level language on IBM i


• Column-oriented coding
• Fixed-format calculations (logic)
• Logic cycle
• Number indicators
• LR (last record)

© Copyright IBM Corporation 2002, 2014

Figure 1-2. RPG IV's legacy AS068.1

Notes:
Report Program Generator (RPG) IV (fourth generation) is by far the most commonly used
programming language on the AS/400, AS/400e, and i systems.
You probably heard many things about the language. Many of the facts that you heard or read do
not apply to the latest version of the RPG IV compiler.
Version 7.1 is the one that we use in this class.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-3


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

What is RPG IV?


IBM i

• Is available beginning with OS/400 Version 3 Release 1


• Is a component of IBM Rational Development Studio for i
licensed program (5770-WDS)
• Expanded or eliminated language limits
• Fulfilled RPG programmers' requirements at that time:
– Longer field names
– Free form expressions
– Date and time calculations support
• Positioned for future growth
• ILE:
– Part of OS/400 beginning with version 2 release 3
– Provides toolset to support and encourage modular code development

© Copyright IBM Corporation 2002, 2014

Figure 1-3. What is RPG IV? AS068.1

Notes:
RPG IV is named ILE RPG. Let us break up ILE RPG into the two components that they really are.
ILE is the development environment and RPG IV is the programming language.
The Integrated Language Environment (ILE) provides the facilities that enable RPG IV programs to
be written in a very modular fashion without the same level of overhead required by RPG III.
Modules of code can be written in a generic, reusable manner so that they can be shared by many
application programs. ILE helps improve application execution efficiency and programmer
productivity.
RPG IV is the name that IBM gave the latest version of the RPG language. It is packaged as part of
the ILE RPG for i compiler. This package of software includes RPG IV and other support, such as
support for RPG/36. We might use the term RPG/400 in this class. We try to differentiate between
RPG IV features and features that were included in the previous version of the language (known as
RPG III). All previous versions of RPG on the i that were packaged as part of RPG/400 are now a
part of the ILE RPG for i package.
The term ILE RPG can be confusing. The RPG IV compiler, officially named IBM Integrated
Language Environment RPG IV for i is one component of the Rational Development Studio for i,
Program Number 5770-WDS.

1-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty ILE RPG for i is the IBM implementation of RPG on the i and AS/400e system. Also, following are
included in 5770-WDS:
• RPG/400
• System/36-Compatible RPG II
• System/38-Compatible RPG III
• ILE RPG IV previous compiler
The Rational Development Studio for i packages the ILE RPG IV for i compiler component together
with other development components. Users can select to install those components that best fit their
application development needs.
You do not have to use the ILE features of binding, sub-procedures, and so forth, to write RPG IV
programs that work and perform the tasks you require.
The RPG/400 component above is the RPG III for i compiler. This class discusses the development
of RPG IV programs only.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-5


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Application development tools: Packaging


IBM i

I V5.4 I V6.1 i V7.1 and 7.2


5722WDS 5761WDS 5770WDS
*Base Feature: ILE Compilers
Option 21 ADTS • Option 31 ILE RPG
Option 31 ILE RPG • Option 35 ILE RPG *PRV Compiler
Option 32 S/36 • Option 41 ILE COBOL
Compatible RPGII • Option 45 ILE COBOL *PRV Compiler
• Option 51 ILE C
Option 33 S/38
• Option 52 ILE C++ RDi RPG + COBOL tools
Compatible RPGII • Option 56 IXLC for C/C++
Option 34 RPG/400 RDi + Java
Option 35 ILE RPG *PRV
Compiler RDi + EGL
Option 41 ILE COBOL Feature: Heritage Compilers
• Option 32 S/36 Compatible RPG II
Option 42 S/36
• Option 33 S/38 Compatible RPG II
Compatible COBOL • Option 34 RPG/400 (RPG III)_
Option 43 S/38 • Option 42 S/36 Compatible COBOL
Compatible COBOL • Option 43 S/38 Compatible COBOL
Option 44 OPM COBOL • Option 44 OPM COBOL
Option 45 ILE COBOL
*PRV Compiler
Option 51 ILE C
Feature: ADTS (no longer enhanced)
Option 52 ILE C++ • Option 21 ADTS
Option 56 IXLC for C/C++ • Option 60 Workstation Tools

© Copyright IBM Corporation 2002, 2014

Figure 1-4. Application development tools: Packaging AS068.1

Notes:
There is one application development product available for i programmers. The product is called the
Rational Development Studio for i (5770-WDS) which includes:
i compilers:
• ILE RPG
• ILE COBOL
• ILE C
• ILE C++
You install only the compilers and features that you need for your installation. The difference is that
now all compilers and tools are included as a single packaged offering.
Application Development ToolSet (no longer enhanced):
• Source entry utility (SEU)
• Screen design aid (SDA)
• Report layout utility (RLU)

1-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • Data file utility (DFU)


• Character generator utility (CGU)
• Advanced printer function (APF)
• Programming Development Manager (PDM)
• Interactive source debugger (ISDB)
• File compare and merge utility (FCMU)
The Rational Development Studio for i (RDS) also includes limited licenses to use the
workstation-based toolset named Rational Development for i (RDi). RDS at IBM i releases 5.4,
6.1 and 7.1 all cooperatively work with the client PC program RDi.
RDi packages the following:
• LPEX Editor
• Remote System Explorer
• Debugger
• i Project
• Screen Designer
• Report Designer
• Application Diagrammer
Rational Developer for i RPG and COBOL + modernization tools, EGL edition is additional
PC-licensed code that, when purchased, adds the following features:
• Host Access Transformation Services (HATS) Toolkit
• Rational Business Developer (RBD)
• Enterprise Generation Language (EGL)
Rational Developer for i RPG and COBOL + modernization tools, Java edition is additional
PC-licensed code that, when purchased, adds the following features:
• Host Access Transformation Services (HATS) Toolkit
• Rational Application Developer (RAD)
• WAS Liberty
• Web and Mobile Web (Worklight)
RDi plus either Java or EGL can be used to modernize existing RPG and COBOL business
applications to the web, mobile devices or into web services.
Starting with IBM i 6.1, WDS was packaged into three separately priced optional features: ILE
compilers, heritage compilers, and ADTS (legacy development tools). Modernized shops now have
the option of ordering the appropriate i optional features as well as the appropriate PC client
software. Now shops can choose RDi to use with WDS or RDi plus Java or EGL (at additional cost).
Entitlement on 5761-WDS and 5770-WDS ILE Compilers, Heritage Compilers, and ADTS features
are based on a maximum number of users per processor tier.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-7


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Development cycle
IBM i

• Define the problem


• Design the solution
• Write the program
• Test and debug the program
• Document the program
• Maintain the program

© Copyright IBM Corporation 2002, 2014

Figure 1-5. Development cycle AS068.1

Notes:
Developers develop a solution to solve a business problem. This visual describes a simplistic
methodology for developing a solution and maintaining that solution over time.
1. The program development cycle begins with understanding the problem.
2. When you understand the business problem, you can design a solution to the problem.
3. Your design must then be expressed in RPG IV code. It is good practice to use formal design
tools to express the solution before attempting to write your RPG IV program. Flow charts,
Warnier-Orr diagrams or pseudocode are all valid choices for documenting the logic of your
program. Here is where most of the heavy thinking takes place. Spend the time here to develop
a correct, well-structured design that addresses the problem. Time spent here could well result
in time saved fixing problems later.
Writing the program involves translating your design into corresponding RPG IV specifications.
Inexperienced developers find this difficult, at first, because they are unfamiliar with language
rules and syntax. This part of the process becomes more mechanical and requires less thought
with time. Most of your thinking is in the design stage...not the writing.

1-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty Typing the program involves using an editor to input program statements into the computer.
Again, the more you use the editor, the more familiar this tool becomes.
4. Testing the program is next. What are you looking for during this test? First, look for any syntax
errors. Syntax errors are errors in the use of the language. These errors are often discovered by
the editor as you key the source statements. Those that happen to get past the editor are surely
flagged by the compiler during compile attempts. Next, look for logic errors. Logic errors are
errors of design. The programmed solution does not work as intended or does not perform the
required functions. It is the programmer's responsibility to verify the accuracy of output from the
program. To debug your programs is to correct the errors found.
5. Documenting the program can take many forms. Internal documentation in the form of
comments in the code can be very helpful to other programmers responsible for later
maintenance of this program. Program flowcharts, application manuals, and operator
instructions could also provide valuable information for later maintenance.
6. When the program has been designed, written, tested, and debugged, it is then ready to be
used. Actual use of the code in live situations often lead to the need for fixes or corrections.
Maintenance is a fact of life; so remember to document your programs well to make the
maintenance effort as painless as possible for yourself or anyone else.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-9


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Describing a programming solution


IBM i

• Print headings
• Read an employee record
• Do while more records exist:
– Count each employee record read
– Write detailed employee information
– Read an employee record
• Print total number of employees
• End program

© Copyright IBM Corporation 2002, 2014

Figure 1-6. Describing a programming solution AS068.1

Notes:
Suppose that you were asked to write a program that prints a report that displays one line item for
each employee on staff, listing each employee’s name, serial number, department, and employee
type. After all employee records were read, your report should print a total count of employees.
As we show in this visual, you might first express the problem using pseudocode in order to
structure and think through a solution.
Some tool would need to be used to depict the wanted report layout, perhaps a printer layout form,
or a GUI tool such as the RDi Report Designer.
The employee data file documentation would provide the needed data specifications for the record
formats.

1-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

RPG IV terminology
IBM i

• Indicators
• Reserved words
• Procedure
• Fields
• Procedural processing
• Page overflow
• Figurative constants
• Specifications
• Opcodes

© Copyright IBM Corporation 2002, 2014

Figure 1-7. RPG IV terminology AS068.1

Notes:
Modern RPG IV programs use procedural logic to manipulate data records. You control how the
fields (RPG IV variables) from the record are manipulated by coding operation codes in your
program. Operation codes can be coded inline or better, in reusable units such as subroutines or
subprocedures.
Field naming follows the rules of symbolic naming; a field can be up to 4096 characters long
(usually 10 - 14 characters in reality). The first character of the name must be alphabetic (A through
Z, $, #, @) with the remaining characters alphabetic (A through Z, $, #, @, _(underscore)) or
numeric (0 through 9). Blanks are not allowed.
RPG IV provides a number of productive features to ease the coding effort. Indicators and figurative
constants are two such features.
The indicators that we use in this class are called named indicators. Named indicators are not the
numbered indicators you may have heard about or even seen. They are actual variable names that
you reference in your logic. Because they have names, your code is much more easily understood
and thus more easily maintained.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-11


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

RPG IV specifications
IBM i

• Seven types of specifications:


– (H or Ctl-opt) Control specifications
– (F or Dcl-f) File description specifications
– (D or Dcl-d, Dcl-ds, Dcl-c) Definition specifications
– (I) Input specifications
– (C) Calculation specifications
– (O) Output specifications
– (P or Dcl-p) Procedure specifications
• Specific functions
• Optional
• Fixed-position and free-form

© Copyright IBM Corporation 2002, 2014

Figure 1-8. RPG IV specifications AS068.1

Notes:
RPG IV programs consist of various types of lines of code, called specifications. Each specification
has a specific purpose. Specifications can be fixed-position entries, meaning that the location of an
entry within a line of code is critical to its interpretation or free form through the use of keywords. We
show you both during this class.
The overall order of the specification types within the program is critical. If they are not grouped in
the proper order when the program is compiled, the program object is not created. The order of
specifications in a program must be as follows:
• H
• F
• D
• I (can’t be free-form)
• C
• O (can’t be free-form)
• P

1-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty H, F, D, and C specs are used throughout this class. Because all files are externally described, you
never code I(nput) or O(utput) specifications in this class. The compiler generates them for you
based on external file and format definitions. Your compilation listings show you all coding
specifications, both coded and generated.
P(rocedure) specifications are used to write modular code that can be accessed (or called) by other
programs. You learn about subprocedure and use the P-spec later but more in the class that follows
this one.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-13


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Print program: RPG code


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 1-9. Print program: RPG code AS068.1

Notes:
This visual is a programming interpretation of the example we discussed using the pseudocode
description earlier in the book. This is a basic print program:
• Each record of the EMPMASTER file is read.
• A copy of each record read is printed on a report.
• The program continues until end of file is reached.
• At end of file EMPMASTER, a total record is written on the report and the end of program indicator
known as last record (*InLR) is set on.

1-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Print program: Report


IBM i

PAGE 1 EMPLOYEE INFORMATION

NAME SERIAL # DEPT TYPE

Haas,C 000010 A00 REGULAR


Thompson,M 000020 B01 MANAGER
Kwan,S 000030 C01 MANAGER
Geyer,J 000050 E01 MANAGER
Stern,I 000060 D11 MANAGER
Pulaski,E 000070 D21 MANAGER
Henderson,E 000090 E11 MANAGER
Spenser,T 000100 E21 MANAGER
Lucchesi,V 000110 A00 REGULAR
: : : :
: : : :
: : : :
Marino,S 000240 D21 REGULAR
Smith,D 000250 D21 REGULAR
Johnson,S 000260 D21 REGULAR
Perez,M 000270 D21 REGULAR
Schneider,E 000280 E11 REGULAR
Parker,J 000290 E11 REGULAR
Smith,P 000300 E11 REGULAR
Setrignt,M 000310 E11 REGULAR
Mehta,R 000320 E21 REGULAR
Lee,W 000330 E21 REGULAR
Gounot,J 000340 E21 REGULAR

NUMBER OF EMPLOYEES 32

© Copyright IBM Corporation 2002, 2014

Figure 1-10. Print program: Report AS068.1

Notes:
The output from our program might appear as above. The layout of the report EMPREPORT is defined
using data description specifications (DDS).
We discuss DDS in a later unit.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-15


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Create RPG IV program


IBM i

Enter
RPG source

Syntax
Using LPEX checking
*FILE

Source
Listing of file
source code Create RPG program
and errors CRTBNDRPG PROGA
(Compile RPG source)
PROGB
*PGM PROGC
Program
object
Test RPG
program by
User steps executing
Data paths

© Copyright IBM Corporation 2002, 2014

Figure 1-11. Create RPG IV program AS068.1

Notes:
You enter an RPG IV program as source code using the Rational Developer for i systems editor,
LPEX.
When your program has been entered and saved, it can be translated into machine-readable object
code. Syntax checking of your program occurs while you are keying.
A unique feature of the LPEX Editor is that you can verify that your program compiles successfully,
before invoking the compiler on the i.
The translation of your source code into an executable program object (*PGM) is accomplished by
compiling your program. If your program has no compilation errors, your program successfully
compiles and an executable object is created.
Now, you must test your program. If there are no logic errors, you have completed your task. If logic
errors do exist, you need to correct them using the editor and recompile the program. This
recompile incorporates the changes into the object program.
A method of stepping through your code using the source debugger is described in the next class,
advanced RPG, AS10.

1-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

IBM i source physical file


IBM i

Format SRCSEQ 6 2
SRCDAT 6 0
SRCDTA 100
PROGA

PROGB Data records


Members (source statements)

PROGC

© Copyright IBM Corporation 2002, 2014

Figure 1-12. IBM i source physical file AS068.1

Notes:
A source physical file is a special file on the i that contains one or more source members. In our
case, our source file contains RPG IV source. Notice that the record format of this file is perfect for
keying source statements. Statement number, date entered, and a field for source statement data
are all you need to enter various kinds of source statements.
The CL command CRTSRCPF creates a similar source file in the library of your choice. For example:
Create Source Physical File (CRTSRCPF)

Type choices, press Enter.

File . . . . . . . . . . . . . . QRPGLESRC Name


Library . . . . . . . . . . . AS0600LIB Name, *CURLIB
Record length . . . . . . . . . 112 Number
Member, if wanted . . . . . . . *NONE Name, *NONE, *FILE
Text 'description' . . . . . . . ILE RPG IV source

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-17


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

F3=Exit F4=Prompt F5=Refresh F10=Additional parameters F12=Cancel


F13=How to use this display F24=More keys

This command creates a source file for RPG IV source members in the AS0600LIB library.
You create a new member, for example, ITEMINQ, in the QRPGLESRC source file, by right-clicking
QRPLESRC and selecting new->member and putting in the member name, type, and text.

1-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

The process of creating an RPG IV program


IBM i

• ILE programs might contain one or more modules.


• For single module programs: CRTBNDRPG.

*MODULE X *PGM X

RPG CRTBNDRPG
source Procedure Procedure
member X X

© Copyright IBM Corporation 2002, 2014

Figure 1-13. The process of creating an RPG IV program AS068.1

Notes:
The CRTBNDRPG command creates an executable program object using one command. Use this
command only in this class to create your executable program objects.
You can click the compile option in LPEX and specify the CRTBNDRPG command. You can set this
command as your individual default.
Look at the figure above and notice the object *MODULE. A module is an i object type for RPG IV
as well as other compilers. The *MODULE object that is created as part of the CRTBNDRPG command
is automatically deleted after the *PGM object has been created.
Each RPG IV module contains what is called a Procedure, which is the entry point into the
executable code contained in that module.
There is another method of creating RPG IV programs that involves creating programs from one or
more modules. The class that follows this one discusses modules and how to combine them to
create programs.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-19


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

CRTBNDRPG compile options


IBM i

• GENLVL(10)
• OPTION():
– *XREF/*NOXREF
– *GEN/*NOGEN
– *SHOWCPY/*NOSHOWCPY
– *NOSECLVL/*SECLVL
– *EXPDDS/*NOEXPDDS
– *EXT/*NOEXT
• DBGVIEW(*STMT)
• OUTPUT(*PRINT/*NONE)
• REPLACE(*YES)
• TRUNCNBR(*YES)
• TGTRLS(*CURRENT)
• PGMINFO(*PCML *ALL)
© Copyright IBM Corporation 2002, 2014

Figure 1-14. CRTBNDRPG compile options AS068.1

Notes:
Default values are shown for each parameter. For the OPTION parameter, the first value of each pair
is the default.
• GENLVL specifies whether a program object is generated, depending on the severity level of the
errors encountered. Valid entries that act as program generation filters are 1 - 20.
• OPTION specifies the options to use when the source member is compiled. You can specify any
or all of the options in any order. Separate the options with one or more blank spaces.
- *XREF produces a cross-reference listing.
- *GEN will create a program object if the severity level specified on GENLVL is not exceeded.
- *SECLVL prints second-level message text on the line following the first-level message text
in the Message Summary section of the compile listing.
- *SHOWCOPY includes any source members copied into the compiled member using the
/COPY directive.
- *EXPDDS shows the expanded definitions of externally described files.
- *EXT shows a listing of external procedures and fields.

1-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • DBGVIEW sets which level of debugging is available. The choices are *STMT, *SOURCE, *LIST,
*COPY, *ALL and *NONE. The corresponding view is then available upon debugging the
compiled object.
• OUTPUT determines if a compile listing is produced.
• REPLACE allows automatic deletion and replacement of a previously compiled program without
a reminder message.
• TRUNCNBR specifies whether a truncated value is moved to the result field or if an error is
generated when numeric overflow occurs while running the program. This parameter has no
effect on calculations done in expressions. We discuss expression calculations and the
precision of those calculations in a later unit.
• TGTRLS specifies the release level of the IBM i, i5/OS (OS/400) system on which you intend to
run the program object being generated.
• PGMINFO specifies whether to generate program call method language that can be used by
web services.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-21


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Compiler listing
IBM i

Listing Section Option Description


Prologue Compile option summary
Source listing: Source specifications
In-line diagnostic messages error by line
*SHOWCPY
/COPY members /COPY source members
Externally described files *EXPDDS record, field, specifications
Additional diagnostic messages Errors spanning multiple lines
Output buffer positions Program described output specs list
/COPY member table of copy members
Arrays Array records
Tables Table records
Key field information *EXPDDS Key field attributes
Cross-reference table *XREF File, record, field indicator use
External references *EXT List of external procedures/fields
Message summary Messages, number of occurrences
*SECLVL
Second-level test second-level message text
Final summary Final compilation message
Code generation errors Error during code generation
© Copyright IBM Corporation 2002, 2014

Figure 1-15. Compiler listing AS068.1

Notes:
Compiler listings provide you with information regarding the correctness of your code with respect
to language syntax and semantics. They are designed to help you detect and correct any errors
through a source editor. This chart summarizes compiler keywords with their associated listing
information.
The following compiler directives can be included in your source code in order to customize your
compile listings:
/TITLE specifies heading information at the top of listing pages:
/TITLE Your text for title information
/SPACE specifies line spacing within the source section of listing:
/SPACE xxx (where xxx = positive integer 1 - 112)
/COPY copies/inserts records from other files into this member:
/COPY MYLIB/MYFILE,mymember
/EJECT sets subsequent specs to begin on a new page of the listing.

1-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Compiler directives
IBM i

• Format the listing:


– /TITLE
– /EJECT
– /SPACE
• Include other members in the compilation
– /COPY
• Conditionally include or exclude code:
– /DEFINE
– /UNDEFINE
• Free format coding group:
– /FREE
– /END-FREE
• Documentation and readability
– * or //
From version 5, use // for all comments.
© Copyright IBM Corporation 2002, 2014

Figure 1-16. Compiler directives AS068.1

Notes:
The compiler directive statements /TITLE, /EJECT, /SPACE, and /COPY allow you to specify
heading information for the compiler listing to control the spacing of the compiler listing to insert
records from other file members during a compile, and to select or omit source records.
/TITLE (Positions 7-12)
Use the compiler directive /TITLE to specify heading information (such as security classification or
titles) that is to appear at the top of each page of the compiler listing. The following entries are used
for /TITLE:

Positions Entry
--------- -----
7-12 /TITLE
13 Blank
14-100 Title information
A program can contain more than one /TITLE statement. Each /TITLE statement provides heading
information for the compiler listing until another /TITLE statement is encountered. A /TITLE

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-23


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

statement must be the first RPG specification encountered to print information on the first page of
the compiler listing. The information specified by the /TITLE statement is printed in addition to
compiler heading information.
The /TITLE statement causes a skip to the next page before the title is printed. The /TITLE
statement is not printed on the compiler listing.
/EJECT (Positions 7-12)

Positions Entry
--------- -----
7-12 /EJECT
13-49 Blank
50-100 Comments

Enter /EJECT in positions 7 - 12 to indicate that subsequent specifications are to begin on a new
page of the compiler listing. Positions 13 - 49 of the /EJECT statement must be blank. The
remaining positions can be used for comments. If the spool file is already at the top of a new page,
/EJECT will not advance to a new page. /EJECT is not printed on the compiler listing.
/SPACE (Positions 7-12)
Use the compiler directive /SPACE to control line spacing within the source section of the compiler
listing. The following entries are used for /SPACE:

Positions Entry
--------- -----
7-12 /SPACE
13 Blank
14-16 A positive integer value from 1 through 112 that
defines the number of lines to space on the
compiler listing. The number must be left-adjusted.
17-49 Blank
50-100 Comments

If the number specified in positions 14 - 16 is greater than 112, 112 will be used as the /SPACE
value. If the number specified in positions 14 - 16 is greater than the number of lines remaining on
the current page, subsequent specifications begin at the top of the next page.
/SPACE is not printed on the compiler listing, but is replaced by the specified line spacing. The line
spacing caused by /SPACE is in addition to the two lines that are skipped between specification
types.
/COPY (Positions 7-11)
The /COPY compiler directive causes records from other files to be inserted, at the point where the
/COPY occurs, with the file being compiled. The inserted files can contain any valid specification
including /COPY up to the maximum nesting depth specified by the COPYNEST keyword on the
H-spec (32 when not specified).

1-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty The /COPY statement is entered in the following way:

Positions Entry
--------- -----
7-11 /COPY
12 Blank
13-49 libraryname/filename,membername
Identifies the location of the member to be
copied (merged).
50-100 Comments

* (Position 7)
The comment directive is one that should be used more frequently than any other. An asterisk (*) in
column 7 of any specification makes that spec a comment regardless of anything else in the spec.
Conditional Compilation Directives
The conditional compilation directive statements allow you to conditionally include or exclude
sections of source code from the compilation.
Condition-names can be added or removed from a list of currently defined conditions using the
defining condition directives /DEFINE and /UNDEFINE.
Condition expressions DEFINED(condition-name) and NOT DEFINED(condition-name) are used
within testing condition /IF groups.
Testing condition directives, /If, /ElseIf, /Else, and /EndIf, control which source lines are to be read
by the compiler.
The /EOF directive tells the compiler to ignore the remaining lines of code in the current source
member.
/DEFINE (Positions 7-13)
The /DEFINE compiler directive defines conditions for conditional compilation. The entries in the
condition-name area are free format (do not have to be left justified). The following entries are used
for /DEFINE:

Positions Entry
--------- -----
7 - 13 /DEFINE
14 Blank
15 - 80 condition-name
81 - 100 Comments

The /DEFINE directive adds a condition-name to the list of currently-defined conditions. A


subsequent /If DEFINED(condition-name) would be true. A subsequent /If NOT
DEFINED(condition-name) would be false.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-25


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

/UNDEFINE (Positions 7-15)


Use the /UNDEFINE directive to indicate that a condition is no longer defined. The entries in the
condition-name area are free-format (do not have to be left justified).

Positions Entry
--------- -----
7 - 15 /UNDEFINE
16 Blank
17 - 80 condition-name
81 - 100 Comments

The /UNDEFINE directive removes a condition-name from the list of currently-defined conditions. A
subsequent /IF DEFINED(condition-name) would be false. A subsequent /IF NOT
DEFINED(condition-name) would be true.
/FREE and /END-FREE
The /FREE compiler directive specifies the beginning of a free-form calculation specifications block.
/END-FREE specifies the end of the block. Positions 12 - 80 must be blank. The remaining
positions can be used for comments. These directives are no longer needed in the latest version of
the code. You will see them in older versions where free-form calculations were used.

1-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Machine exercise: Coding and compiling RPG IV


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 1-17. Machine exercise: Coding and compiling RPG IV AS068.1

Notes:
Perform the Coding and compiling RPG IV exercise.

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-27


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Checkpoint (1 of 2)
IBM i

1. True or false: Today’s RPG IV programs must use ILE features such as binding
and subprocedures.

2. To create a program from an RPGLE type source member, which of the following
answers is correct?
a. CRTRPGPGM
b. CRTBNDRPG
c. CRTRPGMOD and CRTPGM
d. CRTRPGMOD

3. True or false: To include code from another source member in your RPG IV
program, you would use the /COPY compiler directive.

© Copyright IBM Corporation 2002, 2014

Figure 1-18. Checkpoint (1 of 2) AS068.1

Notes:

1-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Checkpoint (2 of 2)
IBM i

4. Number the following RPG specification types in correct sequence.


_ Procedure specifications
_ Input specifications
_ File specifications
_ Definition specifications
_ Control specifications
_ Output specifications
_ Calculation specifications

5. A source physical file for RPG IV source members has a _____ byte
record length?
a. 80
b. 92
c. 100
d. 112

© Copyright IBM Corporation 2002, 2014

Figure 1-19. Checkpoint (2 of 2) AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 1. RPG IV introduction 1-29


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit summary
IBM i

Having completed this unit, you should be able to:


• Explain the general purpose of each RPG IV specification type
• Describe the steps to code and test an RPG IV program
• List several unique features of the RPG language and discuss
RPG's strengths and weaknesses
• Browse an RPG IV compiler listing

© Copyright IBM Corporation 2002, 2014

Figure 1-20. Unit summary AS068.1

Notes:

1-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 2. Coding specifications for RPG IV

What this unit is about


This unit describes the specifications that must be programmer-coded in the
RPG IV language and how each specification is used.
We perform instructor-led desk exercises during lecture to practice coding
specifications, and two machine exercises as we progress through the unit.
We also introduce how a program is structured. This unit familiarizes the
students with the structure of an RPG IV program.
We show the different specification templates in the process of covering the
structure of an RPG IV program. Simple I/O operations such as READ and
WRITE are also introduced.
We perform instructor-led desk exercises during lecture to practice coding
specifications followed by machine exercise at the end of the unit.

What you should be able to do


After completing this unit, you should be able to:
• Describe the purpose of each RPG IV specification type
• Code specifications in the order required for an RPG IV program to
compile successfully
• Describe how to reference externally described database and printer files
in RPG IV
• Write a simple listing program

How you will check your progress


• Checkpoint questions
• Machine exercises
• Given a simple RPG IV program, the class correctly sequences an RPG
IV source member where the specifications are out of sequence.
• Given a problem statement, the students:
- Code and enter an RPG IV program using the SEU or the LPEX
Editor
- Compile the program
- Execute the program
- This program produces a listing of records and places that listing in
the student's OUTQ

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:


• Describe the purpose of each RPG IV specification type
• Code specifications in the order required for an RPG IV
program to compile successfully
• Describe how to reference externally described database and
printer files in RPG IV
• Write a simple listing program

© Copyright IBM Corporation 2002, 2014

Figure 2-1. Unit objectives AS068.1

Notes:

2-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Source specifications
IBM i

Program Data
C Calculation
D Definition
P Procedure
Subprocedure Compile - time array
and table data
O Output **CTDATA
C Calculation Alternate collating
sequence records
I Input **ALTSEQ
D Definition File translation records
F File Definition **FTRANS
H Control
Program Data
Main
Source
Section

© Copyright IBM Corporation 2002, 2014

Figure 2-2. Source specifications AS068.1

Notes:
• Specification type (position 6):
- H, F, D, I, C, O, P, D, C
- Must be coded in this order
• Comment line created by placing * in position 7 or by placing // in position 8 or higher
(recommended method).
• Keywords are used in many specifications.
Because all files that we use are externally described, we do not spend a lot of time on I(nput) and
O(utput) specifications. You are encouraged to review your compiler listings that show the I- and
O-specs that are generated by the compiler. File translation records and alternate collating
sequence records are not mentioned as these are rarely used. Compile time data is mentioned as a
way to initialize arrays but the preferred method of initializing arrays is used in the examples.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Symbolic names
IBM i

• Symbolic names are used for:


– Fields
– Key field lists
– Labels
– Named constants
– Parameter lists
– Record names
• Other RPG names
• Use RPG IV Style Guide suggestions

© Copyright IBM Corporation 2002, 2014

Figure 2-3. Symbolic names AS068.1

Notes:
A symbolic name is a name that uniquely identifies a specific entity in a program or procedure. In
the RPG IV language, symbolic names are used to describe the items in the visual. The rules for
specifying symbolic names are:
• The first character of the name must be alphabetic (the characters $, #, and @ are valid).
• The remaining characters must be alphabetic or numeric, including the underscore (__).
• The name must be left-adjusted in the entry on the specification form except in fields that allow
the name to float (definition specification, keyword fields, and the extended factor two field).
• A symbolic name cannot be an RPG IV reserved word.
• A symbolic name can be 1 - 4096 characters.

2-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Note

The practical limits are determined by the size of the entry used for defining the name. A name that
is up to 15 characters can be specified in the Name entry of the definition or procedure
specification. For names longer than 15 characters, use a continuation specification.

A symbolic name must be unique within the procedure in which it is defined.


RPG IV style tip
In the ITSO Redbook, Who Knew You Could Do That with RPG IV?, there is a reference to the
RPG Style Guide. We reference it and suggest coding style tips for you to consider. Here are some
tips for your RPG:
• Make sure that your names fully and accurately describe an item.
• Use mixed case to enhance the meaning of the name.
Generally, avoid using special characters. However, there are exceptions.
References:
1. Who Knew You Could Do That with RPG IV?, Chapter 2, Programming RPG IV with Style
2. ILE Concepts, Chapter 2, ILE Basic Concepts
A copy of the RPG IV Style Guide is included as an appendix of this notebook.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Field naming rules


IBM i

• First character must be alphabetic.


• Rest may be alpha, numeric or $, #, @.
• Name may be up to 4096 in length.
– Recommend meaningful names
• Mixed case is valid.
– Use mixed case to create meaningful names.
– Must be unique: Compiler converts all to uppercase.
– LastName = lastname = LASTNAME.
• If long name is necessary, you may continue using ellipsis
(...) (unless using free form declarations).

© Copyright IBM Corporation 2002, 2014

Figure 2-4. Field naming rules AS068.1

Notes:
This visual emphasizes the rules for naming fields. Although long names are supported, you can
see that coding them can be awkward. Not shown in the visual, continuation is done using an
ellipsis (...). Free format avoids the need for an ellipsis usually. It would most often be necessary
when using fixed format.
The RPG IV Style Guide recommends that you limit your names to 10 to 14 positions whenever
possible, and that you avoid using any special characters, $, #, @.
Use mixed case to make the use of the field clear.

2-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

RPG IV indicators
IBM i

• Are switches
• Are used to test status of data (+, -, 0, blank, nonblank, >, <)
• Can condition logic flow of calculations and output produced
• Include:
– 01 - 99 general purpose
– Special purpose LR (Last Record) represented as *inLR
– Not necessary to declare explicitly numbered indicators
– Named indicators can map to numbered indicators in Definition specifications - named indicator
variables must be defined (except printer overflow)
• Examples:

Dcl-s Exit ind;

Dow NOT Exit;


Read Record;
// process record...
Enddo;

• Can also be externally defined in DDS (PRTF/DSPF)


© Copyright IBM Corporation 2002, 2014

Figure 2-5. RPG IV indicators AS068.1

Notes:
An indicator is a one position character field that contains one of two possible values:
1. A value of on, also known as true, represented by a 1
2. A value of off, also known as false, represented by 0
An indicator is generally used to indicate the result of an operation or to condition (or control) the
processing of an operation.
Indicators are defined either by an entry on the specification or by the RPG IV program itself. The
positions on the specification in which you define an indicator determine how the indicator is used.
An indicator that has been defined can then be used to condition calculation and output operations.
The RPG IV program sets and resets certain indicators at specific times during the program cycle.
In addition, the state of most indicators can be changed by calculation operations.
The most common ways to set an indicator are by using an expression. Often, you see indicators
set on and off using *on and *off. *on and *off are RPG IV figurative constants.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Machine exercise: Sequencing RPG IV


specifications and compiling
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 2-6. Machine exercise: Sequencing RPG IV specifications and compiling AS068.1

Notes:
Let us practice understanding the order in which RPG IV specifications must be sequenced. In this
exercise, you are given a program that is not in the correct order. Rearrange the specifications and
compile the source to create an executable program.
Perform the Sequencing RPG IV specifications and compiling exercise.

2-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Control specification (H)


IBM i

• Free format
• Keyword driven
• Style:
– One keyword per line
– Leave space after H in fixed form
© Copyright IBM Corporation 2002, 2014

Figure 2-7. Control specification (H) AS068.1

Notes:
The control specification describes your program’s requirements for compilation and runtime by
using keywords and parameter values for those keywords.
The examples show the same H specs, one coded in fixed format with the H in column 6 and the
other using the free form ctl-opt version.
You do not have to code a control specification. If you do not include control specifications in your
source code, the system searches for them in two data areas. In this class, you should write code
for control specs in your programs.
• RPGLEHSPEC in *LIBL during compile time
• DFTLEHSPEC in QRPGLE
If the specifications are not found in either place, the keywords are assigned their system defaults.
If multiple keywords are required, they can be listed on consecutive lines, separated by a blank,
until finished.
Many development shops put the standard control specs they want in all programs in a source
member and use a /COPY statement at the beginning of the program to bring them in.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Style tip
Use the control spec to code your compilation and runtime options. By doing this, you include in the
source code specific documentation about how your program is to be compiled and executed. Also,
code only one keyword per line.
Reference:
ILE RPG Language Reference Manual, Chapter 12, Control Specifications

2-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Control specification keywords


IBM i

RPG IV Keyword Meaning


AltSeq Alt. collating seq. table
Aut Specifies authority
CurSym Currency symbol
DatFmt Default date format
Debug Dump statements executed
DecEdit Decimal notation
DftName Program or module ID
Main Specifies main procedure name
TimFmt Time format

© Copyright IBM Corporation 2002, 2014

Figure 2-8. Control specification keywords AS068.1

Notes:
This is a list of some of the control spec keywords. See Control Specification Keywords in the
Control Specification section of the Specifications chapter of the ILE RPG Reference Manual for a
complete list and description of all keywords. You can also use the content assist facility of the
LPEX Editor while you edit your program to review the options and to understand how to use a
specific keyword.
• Date and Time formats should be specified unless the system defaults are adequate.
• Defaults for most other keywords are sufficient.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

File specifications
IBM i

• Defines files to be processed by your program:


– Name of file
– Type (input, output, update, combined)
– Format (program-described or externally described)
– Device (disk, printer, workstation)
• Keywords area to specify additional functions required
© Copyright IBM Corporation 2002, 2014

Figure 2-9. File specifications AS068.1

Notes:
For each file that your program processes, you must define the file in your program. Both of the files
in this figure are externally described (notice the E in column 22 or *ext parameter in the disk
keyword).
In these examples, we are defining two files:
• EmpMaster, a disk file that we read only; we do not change the file (notice the I in column 17 or
usage(*input) in free version).
• EmpReport, a printer file that holds the printed output of the employee records that the program
reads and processes.
Each file requires its own specification line. For fixed-format positions and keywords are used as
needed:
• File name (positions 7 - 16)
• File type (position 17) I, O, U, C
• File designation (position 18) P, S, F
• File format (position 22) F, E

2-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • Device (positions 36 - 42) Disk, Printer, WorkStn


• Keywords (positions 44 - 80)
For free form:
• Dcl-f followed by file name
• File type (disk, printer, workstn) with *ext parameter if externally described
• File usage for disk files (printers are by default output, workstations are by default input/output)
• KEYED keyword for keyed files
• Other keywords
File names are usually 10 characters long or less. The first character of the name must be
alphabetic (A through Z, $, #, @) with the remaining characters alphabetic (A through Z, $, #, @,
_(underscore)) or numeric (0 through 9).
Blanks are not allowed.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

File specification components (1 of 2)


IBM i

Process
File using
declaration record keys
File use
Device
File name
type
Addition
Externally
described

• Free format starting in column 8


• One specification for each file used by program
• Procedural assumed for disk files

© Copyright IBM Corporation 2002, 2014

Figure 2-10. File specification components (1 of 2) AS068.1

Notes:
This visual shows a number of examples of how you may use the file specification to define files.
Columns on the file spec are used to allow you to quickly and easily describe how a file is to be
processed.
The keywords used in RPG IV file specs provide keywords in areas such as defining how to open a
file and what record format to use. These free-format keywords are optionally used to provide
further detail, such as the name of the variable used to access a set of display records known as a
subfile.

2-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

File specification components (2 of 2)


IBM i

Keywords Area

Process
using
File use
record keys Device
File name Addition type
Procedural
Externally
processing described

• Fixed column format except keywords area


• One file specification for each file used by program
© Copyright IBM Corporation 2002, 2014

Figure 2-11. File specification components (2 of 2) AS068.1

Notes:
This visual shows the same file specifications as the previous visual using fixed format.
Programs developed before V7.1 have the fixed columns on this slide. Programs that are changed
or created on V7.1 and beyond can have a mix of fixed or free form.
All of the keywords that are used in RPG IV file specs are available.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Device type and processing


IBM i

USE DISK PRINTER WORKSTN

Y (+ Addition)
Input - (Y)
*INPUT

Y Addition
Output Y (Y)
*INPUT : *OUTPUT

Y (+ Addition)
Update *UPDATE : *DELETE - -
: *OUTPUT

Combined - - Y

(Y): Can define WORKSTN file this way,


but combined is recommended.
© Copyright IBM Corporation 2002, 2014

Figure 2-12. Device type and processing AS068.1

Notes:
This visual shows the ways that a file can be processed depending upon how it is defined in the
program.
Make sure you define a file in a way that is consistent with how you intend to process the data in the
file. Consider whether your disk, printer, or workstation files are used for input, output, both input
and output, or update, and define them appropriately.
In free format, printer files are assumed to be output and workstation files are assumed to be input
or output. You do not need to specify a usage.
In fixed form, update assumed delete as well. With free form, you need to specify *DELTE if you are
going to delete records.

2-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Database processing options


IBM i

• A file can be processed:


– Sequentially:
• By RRN (no Keyed keyword)
• By key value (Keyed keyword)
– Randomly:
• By RRN (no Keyed keyword)
• By key value (Keyed keyword)
• Keyed keyword and opcode determine how file processed
• Sequential by RRN: Consecutive
• Random by RRN: Direct
• RRN: Relative Record Number

© Copyright IBM Corporation 2002, 2014

Figure 2-13. Database processing options AS068.1

Notes:
Processing sequentially by key is also known as indexed sequential processing.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Control and file specifications: Employee print


program
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 2-14. Control and file specifications: Employee print program AS068.1

Notes:
Let us look again at the employee print program.
Can you now see that how the files are defined to the program determines how that file may be
processed?
Notice that both files are externally described and that the disk file is full procedural. If you do not
specify full procedural, you get compilation errors.
How are we processing the file? We are using a Read opcode that says read the next record
(sequential). But, notice also that the disk file has an RAT = K. That means we use the index and
that the file is processed sequentially by key.
Desk exercise
Let us practice some coding at this point. You can code the following on a piece of paper, or, better,
use the system and the LPEX Editor to create the following statements:
Code a control spec that meets these specifications:
• Select your local country's currency symbol to be used in any editing.
• A runtime error is to be generated when numeric overflow is detected.

2-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • The literal, ‘AS06 RPG IV Programming - Fundamentals’ is to be defined as the copyright string
for the program.
Code the file specifications for these files.
Note: All files are externally described. All disk files are full procedural:
• Physical file ORDER (input) to be processed consecutively.
• Logical file CUSTOMER (input) to be processed by key.
• Printer file AUDITLIST; use indicator PageOver to identify page overflow.
• Physical file STOCK (update) to be processed by key, allowing records to be added.
• Display file INQUIRY.
You may use fixed or free form for the control and file specs. Please use free form for the
calculation specs.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Definition specifications
IBM i

• Definition specifications define program working variables:


– Stand-alone fields
– Named constants
– Data structures and their subfields
– Arrays
– Named indicators

© Copyright IBM Corporation 2002, 2014

Figure 2-15. Definition specifications AS068.1

Notes:
The (D)efinition specification allows definition of data items specific to a program (that is, not from a
file). Miscellaneous items, such as stand-alone fields, named constants, data structures, and
arrays, are good examples.

2-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Definition specifications to define data


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 2-16. Definition specifications to define data AS068.1

Notes:
For definition of fixed form columns see the RPG reference manual, Definition Specifications
For free form:
• Dcl-s for stand-alone
• Dcl-c for constant
• Dcl-ds and end-ds for data structures
• Dcl-pi and end-pi for procedure interface
• Dcl-pr and end-pr for procedure prototype
For constants:
• No length required
• Value specified using CONST keyword or specified after name

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Notice continuation of values:


• Character values continued with dash (-) continue with first column in keywords on the
continuation line.
• Character values continued with plus sign (+) continue with first non-blank column in keywords
area of continuation line.
• Numeric values require no continuation character and continue with the first numeric character
on continuation line.
Reference:
ILE RPG Language Reference Manual, Specifications, Definition Specifications

2-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Defining a data structure and array


IBM i

DS - data structure
Name through Phone_No - data structure subfields

Dim(10) - array is a set of 10 elements


5 0 - each element is zoned numeric five digits, zero decimals
© Copyright IBM Corporation 2002, 2014

Figure 2-17. Defining a data structure and array AS068.1

Notes:
Two new concepts are introduced here. Both data structures and arrays are groupings of data:
1. Data structure: A data structure is an area in program storage that can be used to define the
layout of subfields within that area. Data structures can be used to subdivide a single field or to
group subfields into a single structure.
2. Array: A group of related data. All elements same data type. Think of all the telephone numbers
in a telephone directory. Each number is the same data type and length.
In the visual:
• Personal is a data structure containing the subfields Name and Phone_No. Name and
Phone_Number are subfields (or redefinitions of the storage area occupied by Personal).
Notice that subfields are blank in the Ds position of the Definition specifications. Also, notice
that the free form end-ds ends the Dcl-ds while in fixed form the first non-blank value in the
Ds position terminates the subfield definitions within the data structure.
• Array1 is an array of 10 elements, each a zoned numeric field of 5 digits. The DIM keyword is
used to specify how many elements are in the array. You access an individual element of an
array using an index. The index can be a constant or a variable. For example, Array1(3)

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

operates on the third element of the array. Array(Idx) operates on the third element of the array
if Idx = 3.
The example shows the definition of a data structure containing several subfields. Note the
indentation of the subfields to show the structure.
Notice also that both data structures and arrays define groups of data. The subfields in the data
structure do not have to be defined as the same data type and length. The elements of an array
must be defined as the same data type and length.

2-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Where are externally described descriptions?


IBM i

EmpMaster File
name
EMPREC Record format name
EMPNO 6
FIRSTNME 12
MIDINIT 1
LASTNAME 15 Field name and
. attributes key fields
.
.
K EMPNO
EmpMaster
000010 Christine I Haas Member containing
000020 Michael L Thompson
000030 Sally A Kwan data records
000040 John B Geyer
______ ____ _ _______
______ ____ _ _______

© Copyright IBM Corporation 2002, 2014

Figure 2-18. Where are externally described descriptions? AS068.1

Notes:
When you describe a file using DDS (or SQL DDL), the field names, data types, and field lengths
are stored with the object. When you declare a file as externally described, the RPG IV compiler
gets a copy of the record format and automatically generates input (or output) specifications based
on the external definitions.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Input specification for input data


IBM i

*---------------------------------------------------------------------
* RPG name External name
* File name. . . . . . . . . : ITEM_PF AS06V1LIB/ITEM_PF
* Record format(s) . . . . . : ITEM_FMT ITEM_FMT
*---------------------------------------------------------------------
24=IITEM_FMT
*---------------------------------------------------------------------
* RPG record format . . . . : ITEM_FMT
* External format . . . . . : ITEM_FMT : AS06V1LIB/ITEM_PF
* Format text . . . . . . . : Item Master Record
*---------------------------------------------------------------------
25=I P 1 3 0ITMNBR
26=I A 4 28 ITMDESCR
27=I P 29 32 0ITMQTYOH
28=I P 33 36 0ITMQTYOO
29=I P 37 39 2ITMCOST
30=I P 40 42 2ITMPRICE
31=I P 43 45 0VNDNBR
32=I A 46 52 ITMVNDCAT#

© Copyright IBM Corporation 2002, 2014

Figure 2-19. Input specification for input data AS068.1

Notes:
Notice that no field level information is required for the externally described file.
The necessary I(nput) specifications are automatically generated for you by the compiler.
Using externally described files not only saves you coding effort, remember that when you make a
change to a file, all you have to do is recompile the programs that reference the file.
Reference:
• ILE RPG Reference Manual, Specifications, “Input Specifications”

2-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Calculation specifications
IBM i

• Arithmetic functions
• Processing logic:
– Read, write, and update records
– Indicator control
• Conditional execution
• Data manipulation
• Iterative processing

© Copyright IBM Corporation 2002, 2014

Figure 2-20. Calculation specifications AS068.1

Notes:
After you have coded the control specification, defined the files used in the program, and defined
any stand-alone fields, you are ready to code the Calculation specifications used to describe your
program logic and all record I/O, some of which might be controlled by indicators. In the calculation
spec, define exactly what processing needs to be done to meet the requirements defined for a
program.
Reference:
• ILE RPG Reference Manual, Specifications, Calculation Specifications

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Calculation specification structure


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 2-21. Calculation specification structure AS068.1

Notes:
The basic structure of calculation specifications is illustrated in this visual:
1. This visual illustrates calculations. Notice they follow the Definition specifications. If there were
input specs coded in the program, the calculation specs would follow them.
2. In this example, we perform some operations if a condition on the WHEN is satisfied; in this
case a SELECT group is used to set indicators (positive, negative, or zero) based on the value
of Count.

2-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Typical calculations
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 2-22. Typical calculations AS068.1

Notes:
This is our employee listing program once again. One thing we want you to notice is that there is a
loop that is executed until end of file is reached. Notice the %Eof Built-in function that is used to test
whether we have read the last record in the EmpMaster file.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Common opcodes
IBM i
BegSr Begin subroutine
EndSr End subroutine
ExSr Execute a subroutine
Chain Random read with key or RRN
Delete Delete record
DoW Do While condition is true
DoU Do Until condition is not true
Endxx End group (Do, If, and so forth)
Eval Evaluate an expression
Eval-Corr Assign corresponding subfields
ExFmt Write then read a screen with format
For Perform a group of calculations for iterations
If Perform calculations that follow if expression is true
Else Perform calculations that follow when if expression is false
Read Read a record
Return Return to calling program or procedure
Select Begins a Select group
When Part of select; perform calculations based on condition
Other Part of select; catch all after Whens
SetLL Set file cursor at first record
SetGT Set file cursor at last record
Update Update record
Write Write record

© Copyright IBM Corporation 2002, 2014

Figure 2-23. Common opcodes AS068.1

Notes:
This visual shows some of the available operation codes. We use many of them throughout the
remainder of the course. Detailed descriptions of all RPG IV operation codes can be found in the
Reference Manual.

2-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Rules of coding
IBM i
• /Free and /End-free groups:
– Begin with /Free column 7-12 (no longer needed as of 7.1 tech refresh)
– End with /End-Free column 7-16: (no longer needed as of 7.1 tech refresh)
• Column 6 must be blank
• Rest of line must be blank
– Every statement terminated by semicolon;
– Semicolon (;) can follow the end of the statement in any position
– RPG IV code starts in column 8 or higher
– Every statement must begin with the opcode:
• Optional for Eval and CallP
• Only if no extenders
• Operation extender immediately follows opcode --no space
• Opcodes, such as CHAIN, are written opcode Factor1 Factor2 Result;
– Comments (//)
• Can start on separate line in column 8 or higher
• Can be written after semicolon (;) of line of RPG IV code
– Style guideline:
• Use indentation
– Remember:
• Opcodes requiring a resulting indicator are not supported
– Must use free form BiF equivalent
© Copyright IBM Corporation 2002, 2014

Figure 2-24. Rules of coding AS068.1

Notes:
To take advantage of free form syntax, a few basic rules apply:
• The /Free and /End-Free are no longer needed but are syntax checked.
• Nothing is entered in column 6. It must be blank.
• /Free and /End-Free, if coded, must start in column 7. The rest of line must be blank.
• When coding RPG IV statements and comments, columns 6 and 7 must be blank. Every
statement in the block must be terminated by a semicolon.
• Every statement must begin with the opcode (except in the case of Eval where the opcode can
be omitted).
• Comments (//) can start on a separate line beginning in column 8 or later; or they can be coded
following the semicolon (;) that terminates a statement.
• Operation extender must immediately follow the opcode (no blanks).
• Procedure calls with no parameters must be coded with empty parentheses. This is true for both
Eval and Callp (also true for fixed-format coding).

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

These rules differentiate free format calculations from fixed and extended format calculations.
This visual can be used as a reference when you are coding in free format.
Additional rules:
These are included for completeness only. They do not apply at this point in your RPG IV training,
but, they apply as you learn additional techniques:
• Opcodes requiring a resulting indicator are not supported (must use BiFs instead).
• Every statement must begin with the opcode (except in the case of Eval and CallP where the
opcode can be omitted when no extenders are specified).
CallP and extenders are discussed in a subsequent unit.

2-32 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Output specifications
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 2-25. Output specifications AS068.1

Notes:
You should never have to code these specifications by hand. All files should be externally described
including report files. We show you this example for your information only. The output specifications
in this example are generated by the compiler based upon the definitions of the report file.

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Class exercise: Coding a simple listing


IBM i

• Given:
– VENDOR_PF: Vendor physical file
– VENDORPRT: DDS for printer file
• We: Code a program to list all records until end of file reached
– For each record, accumulate a record count
– Print the record count once end of file is reached

© Copyright IBM Corporation 2002, 2014

Figure 2-26. Class exercise: Coding a simple listing AS068.1

Notes:
Before you perform the machine exercise, your instructor leads a class exercise where you write a
listing program. Be prepared to be actively involved and ask a lot of questions.
Your level of involvement benefits you greatly when you write your first program from scratch in the
exercise that follows.

2-34 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Machine exercise: Coding a report program and
adding overflow
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 2-27. Machine exercise: Coding a report program and adding overflow AS068.1

Notes:
Perform the exercises:
• Coding a report program
• Adding overflow

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Checkpoint
IBM i

1. True or false: A control spec must be coded into every RPG IV source
member.

2. Which of the following are functions of the file spec in RPG IV?
a. To reflect the status of the last input operation
b. To designate the file as Input or Output
c. To specify a file described externally or in the program

3. True or false: The Definition specification is NOT needed to define


fields from an externally described file.

© Copyright IBM Corporation 2002, 2014

Figure 2-28. Checkpoint AS068.1

Notes:

2-36 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Unit summary
IBM i

Having completed this unit, you should be able to:


• Describe the purpose of each RPG IV specification type
• Code specifications in the order required for an RPG IV
program to compile successfully
• Describe how to reference externally described database and
printer files in RPG IV
• Write a simple listing program

© Copyright IBM Corporation 2002, 2014

Figure 2-29. Unit summary AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 2. Coding specifications for RPG IV 2-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

2-38 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 3. Data representation and definition

What this unit is about


This unit describes how data can be defined to the RPG IV compiler. It
reviews the various data types and describe how they can be defined to the
database and then brought into your RPG programs. This unit covers the
most commonly used data types: character, indicator, packed and zoned
decimal, as well as integer.

What you should be able to do


After completing this unit, you should be able to:
• List the most common data types supported in RPG IV
• Use D-specifications to define these data types

How you will check your progress


• Checkpoint questions
• Classroom exercise:
- We will assign desk exercises to practice using D-specs to define all
work fields in RPG IV programs.
• Machine exercise:
- Students add file and data definitions as required to an existing
program.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:

• List the most common data types supported in RPG IV

• Use Definition specifications to define these data types

© Copyright IBM Corporation 2002, 2014

Figure 3-1. Unit objectives AS068.1

Notes:

3-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

RPG IV data types


IBM i

AaBbCcDd
12
11 1
10 2
14/2/96

1.45
9 3
8 4 120
7 5
6
100
80
60
40
20
0
1
2 3 4 5 6

1001 1111 1010 1111 1101 0000


1010 1111 0010 1111 0001 1100
© Copyright IBM Corporation 2002, 2014

Figure 3-2. RPG IV data types AS068.1

Notes:
There are many different data types that you can manipulate in your RPG IV programs. To use them
effectively, you must understand how and where they can be used. In the rest of this topic, we
discuss each data type.
Often, the data type and its use are familiar to those with an extensive programming background.
We encourage you to ask lots of questions to make sure you understand how the data type is used
on the i versus any other system or language with which you are familiar.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Character data
IBM i

C 9 C 2 D 4

IBM = 1100 1001 1100 0010 1101 0100

F 1

*IN50 = *ON = 1111 0001

• 1 byte = 1 character
• Data type A

© Copyright IBM Corporation 2002, 2014

Figure 3-3. Character data AS068.1

Notes:
Character, or alphanumeric, data is one of the most common data types. It can be anywhere from 1
byte to 65,535 bytes in length. Character fields are initialized to blanks by the compiler.
You might assume that character data only included data items, such as name fields or address
fields.
In addition, the numeric (and certain special) indicators that RPG IV uses are a 1-character field.
They can be used to condition execution of certain pieces of your code. They can be used to inform
you that a certain record of a specific file has been read to condition logic in your calculations and to
condition output. Indicators have two possible values:
On = ‘1’
Off = ‘0’
Indicators are initialized with the value '0'. There are 99 numeric indicators in RPG IV. You see them
in the following forms:
• 85 means indicator 85 is on (*On or ‘1’).
• N40 means indicator 40 is off (*Off or ‘0’).

3-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • *IN15 means indicator 15 is on (*On or ‘1’).


Indicators might also be represented by an RPG IV field name, as you have seen in previous
examples. We show you the indicator data type in this unit. As we have been showing you in all the
examples so far, you can write all your programs using named indicators rather than using the
numeric indicators that are the character data type.

Note

There are other indicators, such as *INLR, *INOF, *INOV, and so forth. There are over 100
indicators available in the RPG IV language in total.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Numeric data
IBM i

ZONED
F 1 F 2 F 3

123 = 1111 0001 1111 0010 1111 0011

ZONED
F 4 F 5 F 6

456 = 1111 0100 1111 0101 1111 0110

PACKED
4 5 6 7 8 F

456.78 = 0100 0101 0110 0111 1000 1111

Decimal point is IMPLIED.


© Copyright IBM Corporation 2002, 2014

Figure 3-4. Numeric data AS068.1

Notes:
There are several types of numeric data that we discuss. Numeric data in RPG IV is described as a
number of digits including zero or more digits to the right of the implied decimal point. Because the
decimal point is implied, and is not stored with the numeric data, you will not see it when you display
the data. However, when you edit a numeric field with a decimal point, it is included.
A numeric variable is initialized to zero unless you initialize it in your program (on the Definition
spec) to some specific value.
For example, the notation (5 1) means that the field contains five digits in total, four digits to the left
of the decimal and one digit to the right of the decimal. Remember, the decimal is not stored as part
of the number. It is implied.

3-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Zoned decimal
IBM i

ZONE DIGIT SIGN


F 1 F 2 F 3

+123 = 1111 0001 1111 0010 1111 0011

SIGN
F 1 F 2 D 3

-123 = 1111 0001 1111 0010 1101 0011

• 1 byte = 1 digit
• Data type S

© Copyright IBM Corporation 2002, 2014

Figure 3-5. Zoned decimal AS068.1

Notes:
Zoned decimal format requires one byte of storage for each numeric digit. The zone portion of the
byte is set to 1111 and the digit portion is the binary value of the digit. The maximum length is 63
digits (including decimals) beginning with V5R3. (The maximum was 30 digits.)
Zoned formats should be specified for numeric fields when there is a requirement for converting the
numeric data to character data. Zoned numeric is also compatible with numeric data defined in
display and printer files.
X'F' is the positive sign, while X'D' is the negative sign. Other signs are tolerated (A/B/C/E) by the
system and are changed to F or D when they are operated on for the first time.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Packed decimal
IBM i

2 5 6 F

256 = 0010 0101 0110 1111

0 2 5 D

-25 = 0000 0010 0101 1101

• 1 byte = 2 digits
• Data type P

© Copyright IBM Corporation 2002, 2014

Figure 3-6. Packed decimal AS068.1

Notes:
Packed decimal format can hold two numeric digits per byte. The only exception to this is that the
second half of the low-order byte contains the sign for the number. The convention on the i is that
hexadecimal 'F' is positive and hexadecimal 'D' is negative. You may have a total of 63 digits (V5R3
or higher). (The maximum was 30 digits.) Because packed decimal data is stored two digits to a
byte except the low-order byte (which includes the sign), numeric data requires:
(# of digits/ 2) + 1
bytes of storage For example:
6 digits require (6 / 2) + 1 = 4 bytes
9 digits require (9 / 2) + 1 = 5 bytes
Wherever possible, you should define packed fields with an odd number of digits so as not to waste
the first half of the high-order byte. Doing this also reduces the overhead required when operating
on the packed field.
Packed decimal is the default form of numeric data on the i. Numeric calculations are designed to
perform best when they operate on packed decimal data.

3-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty Since most arithmetic in RPG is done in packed format, it makes sense to define numeric data in
this format in order to avoid unnecessary internal data conversion.
Finally, other values for signs are supported to ease exchange of data between systems. You find
them in the ILE RPG Language Reference.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Integer/Unsigned
IBM i

• Integer/Unsigned:
– Data types I/U
– 1, 2, 4, or 8 bytes in length
– 3, 5, 10, or 20 digits

© Copyright IBM Corporation 2002, 2014

Figure 3-7. Integer/Unsigned AS068.1

Notes:
You define an integer field by specifying int for the data type on the declaration specification.
The length of an integer field is defined in terms of number of digits; it can be 3, 5, 10, or 20 digits
long. A 3-digit field takes up 1 byte of storage; a 5-digit field takes up 2 bytes of storage; a 10-digit
field takes up 4 bytes; a 20-digit field takes up 8 bytes. The range of values allowed for an integer
field depends on its length.
Integer (and character) data types are the only formats common across most platforms and
languages and therefore popular if data interchange is a requirement. Application programming
interface (API) usage also demands integer data processing.

3-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty The length determines the range of values as follows:


Field length Range of Allowed Values
____________ _______________________
3 digit signed -128 to 127
5 digit signed -32768 to 32767
10 digit signed -2147483648 to 2147483647
20 digit signed -9223372036854775808 to 9223372036854775807
3-digit unsigned 0 to 255
Field length Range of Allowed Values
____________ _______________________
5-digit unsigned 0 to 65535
10-digit unsigned 0 to 4294967295
20-digit unsigned 0 to 18446744073709551615
The unsigned format is like integer format except that no negative values are allowed.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Named indicators
IBM i

• Use named indicators rather than numeric *Inxx (except *InLR).


• The data type is N.
© Copyright IBM Corporation 2002, 2014

Figure 3-8. Named indicators AS068.1

Notes:
The indicator data type allows you to use a meaningful field name instead of a numeric indicator.
Notice that the data type is N.
In this example, notice the use of a named indicator for overflow, PrtOverflow. It is implicitly
defined. Also, notice the named indicator, NoRec. This indicator is explicitly defined and is set to
the initial value of the end of file indicator after the first read.

3-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Date, Time, and TimeStamp fields


IBM i

• Define on Definition spec or externally using DDS or SQL


• Data types D, T, Z
• Length on Definition spec not required
• Format used in program can be specified (default *ISO)
– Timestamp fields:
• yyyy-mm-dd-hh.mm.ss.mmmmmm only format
• Microseconds optional (compiler will pad with zeros)
• Literals = D'Date value', T'Time value', Z'TimeStamp value'

© Copyright IBM Corporation 2002, 2014

Figure 3-9. Date, Time, and TimeStamp fields AS068.1

Notes:
Date, Time, and TimeStamp data fields can be defined on the Definition spec, on the Input spec (for
program-described files), or they can be brought in from externally described files. These data
types are equivalent to the corresponding DDS data types, except that DDS uses data type ‘L’ for a
date field.
The INZ keyword on the Definition spec allows you to initialize variables with specific values.
Date, Time, and TimeStamp fields do not require lengths to be specified. Their lengths are implicitly
defined based on the data type. If a length is specified, it must be correct for the format. For
example, if the format for a date field is *MDY, the length must be 8 characters, the length of the
edited field. In the case of date formats, the 2-digit year formats are 8 characters long (except
Julian *JUL which is 6) and the 4-digit formats are 10 characters in length.
The default format for dates and times in the program can be specified on the control spec. If no
format is specified on the control spec, then the default format for both date and time fields
throughout the program is *ISO. The formats possible are listed on the next visual.
Literal values can be entered for dates, times, and timestamps. They must be preceded with D, T,
or Z with the value that is specified in single quotation marks. The format of the literal value for the

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

INZ or CONST keywords that are specified on the Definition spec must be in the default format for
the program. This is required even if the format specified on the Definition spec is different.
In the example on this visual, the control spec specifies that the default formats for this program are
*MDY for dates and *ISO for times. Therefore, those are the formats that are used when specifying
the INZ keyword values.
The TimeStamp data type has only one format of 26 characters in length.

3-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

What can be done?


IBM i

• Define date (D), time (T), and timestamp (Z) data on


Definition spec
• Select date and time format (*MDY, *EUR, *HMS)
• Calculate duration between two dates
– Days = %Diff(DateDue : DateShipped : *days)

• Extract components of date, time, and timestamp


– MonthBorn = %SubDt(DateBorn : *m)
• Convert character data to date and time using %Date,
%Time, %TimeStamp
– DateToday = %Date(*date)
• Compare date and time values
• Validate Date, Time, and TimeStamp fields using Test (D/T)
– Test(DE) CharDate

© Copyright IBM Corporation 2002, 2014

Figure 3-10. What can be done? AS068.1

Notes:
This visual lists some of the things you can do with Date, Time, and TimeStamp data types. These
data types make performing date and time-based calculations much easier.
Understanding how to define these types of variables makes it easier for you to use these data
types in calculations.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Date formats
IBM i

Name Description Format Sep Length Example


*MDY Month/Day/Year mm/dd/yy /-.,& 8 01/15/40

*DMY Day/Month/Year dd/mm/yy /-.,& 01/01/40


8

*YMD Year/Month/Day yy/mm/dd /-.,& 40/01/01


8

*JUL Julian yy/ddd /-.,& 94/015


6

*ISO Intl. Stds. Organization yyyy-mm-dd - 1994-01-15


10

*USA IBM USA Std. mm/dd/yyyy / 01/15/1994


10

*EUR IBM European Std. dd.mm.yyyy . 15.01.1994


10

*JIS Japanese Ind. Std. yyyy-mm-dd - 1994-01-15


10

© Copyright IBM Corporation 2002, 2014

Figure 3-11. Date formats AS068.1

Notes:
The column labeled Sep lists valid separators for the date format. The ampersand (&) symbol
indicates a blank is to be used as the separator. The separator character, if different from the default
for the format, is specified by a character that follows the format, for example, *MDY- (05-10-96). Of
course, if no separator is specified, the system uses the default separator for the particular format.
Note that these formats are the same as those provided in DDS for externally described Date fields.
For those formats with a 2-digit year (*MDY, *YMD, *DMY, *JUL), the year can be 40 (1940) through
39 (2039); that is, any year less than or equal to 39 is assumed to be in the 21st century. Any year
greater than or equal to 40 is assumed to be in the 20th century.
There is a *CYMD format also. The century digit can be 0 for dates through 1999, 1 for dates 2000
- 2099, 2 for dates 2100 - 2199, through 9 for dates 2800 - 2899. Making this change in your
database date fields allows you to calculate dates into the 21st century (for example, 096/05/10 is
May 10, 1996; 198/03/15 is March 15, 2098).
There are three kinds of Date data formats, depending on the range of years that can be
represented. This leads to the possibility of a date overflow or underflow condition occurring when

3-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty the result of an operation is a date outside the valid range for the target field. The formats and
ranges are as follows:
Digits -Year Format Range of Years
2 *YMD, *DMY, *MDY, *JUL 1940 to 2039
3 *CYMD, *CDMY, *CMDY 1900 to 2899
4 *ISO, *USA, *EUR, *JIS, *LONGJUL 0001 to 9999
*Cxxx formats cannot be declared or stored. These formats can only be used on MOVEs and
TEST opcodes, and are for compatibility only.
*LONGJUL (Long Julian) is similar to *Cxxx formats except that it is of the form yyyy/ddd
supporting a 4-digit year.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Time formats
IBM i

Name Description Format Sep Length Example

*HMS Hours:Minutes:Seconds hh:mm:ss :.,& 8 14:00:00

*ISO Intl. Stds. Org. hh.mm.ss . 8 14.00.00

*USA IBM USA Std. hh:mm AM : 8 02:00 PM

*EUR IBM European Std. hh.mm.ss . 8 14.00.00

*JIS Japanese Ind. Std. hh:mm:ss : 8 14:00:00

© Copyright IBM Corporation 2002, 2014

Figure 3-12. Time formats AS068.1

Notes:
The Sep column indicates the valid separators for the format. The & symbol indicates a blank is
used for the separator. The separator character, if you want one that is different than the default
format, is specified as a character that follows the format; for example, *HMS&.
TimeStamp fields have a predetermined size and format. TimeStamp data must be in the format:
yyyy-mm-dd-hh.mm.ss.mmmmmm
The TimeStamp data must have a length of 26 characters. Microseconds (mmmmmm) are optional for
TimeStamp literals and if not provided, are padded on the right with zeros. Leading zeros are
required for all TimeStamp data.
Note that these formats are the same as those allowed in the database (DDS or SQL) for externally
described time fields.

3-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Moving data to and from Date, Time, and
TimeStamp
IBM i

• Like to like with format conversion:


– Date to Date, Time to Time, TimeStamp to TimeStamp
– Date or Time to TimeStamp
– TimeStamp to Date or Time

• Date or Time to Character or Numeric


– Use %Char, %SubDt, %Dec

• Character or Numeric to Date, Time, or TimeStamp:


– Use %Date, %Time, %TimeStamp
– Can specify format of input

© Copyright IBM Corporation 2002, 2014

Figure 3-13. Moving data to and from date, time, and timestamp AS068.1

Notes:
Built-in-Functions can help you to move Date, Time, and TimeStamp data in these data types to or
from numeric and character fields. The system knows about proper Date, Time, and TimeStamp
data types but it does not know how the date is formatted in a numeric field. Is it MDY, YMD, 4-digit
year? For a character field, we must tell the system not only the format but also whether there is a
separator character and what it is.
When moving data from a date to another date, for example, no format of the date needs to be
specified as they are stored in a common format. In fact, the parameter (for a BiF usually), which
would contain the format, must be blank if both the source and the target of the move are Date,
Time, or TimeStamp fields.
A 2-digit year format (*MDY, *DMY, *YMD and *JUL) can only represent dates 1940 - 2039. An error
occurs if conversion from a 4-digit year to a 2-digit year format results in a year outside this range.
Because the system does not know the format of the date or time data in the numeric or
alphanumeric field, you must explicitly declare the format that applies. If you do not declare the
format, the system assumes that the format matches that of the date or time field to which you are
assigning the value.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Other data types


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 3-14. Other data types AS068.1

Notes:
For completeness we listed other types of variables you may encounter in RPG IV programs.
Floating point: Another numeric data type. As with packed, zoned and integer data types, floating
point can be used for routine arithmetic operations. It is especially useful for engineering and
scientific calculations where a variable might contain a large range of values – from very small to
very large.
Basing pointer: A pointer contains an address in memory, not a value. Any variable based on a
pointer will therefore map over this memory location. Pointer manipulation is an advanced
programming technique, not for the novice.
Other character types: These data types contain character data. Graphic data uses two bytes to
represent a character rather than just one byte. UCS-2 is a special case of graphic data that is used
by the web to represent data from multiple cultures. Variable length fields (varchar, vargraphic,
varucs2) have either two or four bytes at the start of the field to indicate how long the field is.

3-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Figurative constants
IBM i

• *BLANK/*BLANKS Initialize character or graphic fields


• *ZERO/*ZEROS Initialize character or numeric fields
• *ALL'x..' Initialize character field to string
• *ALLX'F1..' Initialize character field to hex string
• *HIVAL Highest value for data type
• *LOVAL Lowest value for data type
• *ON/*OFF All '1's or '0's (character data only;
usually with indicators)
• *ALLG'ok1k2i' Initialize graphic field to string
• *Null Initialize to nulls
• *START/*END Used to position at the beginning or
end of database files

© Copyright IBM Corporation 2002, 2014

Figure 3-15. Figurative constants AS068.1

Notes:
These are special variables that are supplied to you by the language. You use them just like you
would a variable in your program. They assume the characteristics of the field you're moving them
to.
If you move the string *ALL'xyz' to a five byte field, the field contains 'xyzxy'.
For figurative constraints:
• No length or decimal positions required.
• Adapt to the definition of field operated upon

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Data definition
IBM i

Where can data


be defined in an
RPG IV program?

© Copyright IBM Corporation 2002, 2014

Figure 3-16. Data definition AS068.1

Notes:
RPG allocates only one storage area to each field that you define. You can define the field more
than once if you like, but the definitions must be consistent or you get an error at compilation time.
Even if the field is defined for a second time in another file, it is allocated only one storage area.

3-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Externally described files


IBM i

• Uses definitions in DB2 UDB for i


• Assures consistent file and field names:
– Easier to maintain applications
– Can override field names from database
• Has other uses:
– Parameter list
– Data structure

© Copyright IBM Corporation 2002, 2014

Figure 3-17. Externally described files AS068.1

Notes:
Earlier, we introduced the subject of externally described file descriptions. We contrasted their use
to that of program described file descriptions. Using externally described data is the preferred way
of defining data files. For the reasons stated in the visual, they are much easier to use and maintain.
Next, you are shown an example of how the names of fields in an externally described file could be
made unique within a program.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Defining externally described data


IBM i

112=IVENDOR_FMT
*----------------------------------------------------------------------
* RPG record format . . . : VENDOR_FMT
* External format . . . . : VENDOR_FMT : AS06v6LIB/VENDOR_PF
* Format text . . . . . . : Vendor Master File Record
*----------------------------------------------------------------------
113=I P 1 3 0VNDNBR
114=I A 4 28 VNDNAME
115=I A 29 53 VNDSTREET
116=I A 54 76 VNDCITY
117=I A 77 78 VNDSTATE
118=I P 79 81 0VNDZIPCODE
119=I P 82 83 0VNDAREACD

© Copyright IBM Corporation 2002, 2014

Figure 3-18. Defining externally described data AS068.1

Notes:
You can retrieve the file and field definitions for a record format as simply as this. Remember that
each field is given a storage address only once. If you have the same field name in multiple record
formats or in different files, they will share one storage address.
Externally described files have an E on the File spec as shown to indicate an external file definition.
These definitions are copied into the program at compile time.
If the database format of Vendor_PF changes, all you have to do is recompile this program to
implement the changes. If the program and database definitions do not match, the system informs
you of the problem with a Level Check message. The nice feature is that you do not have to
change the program's record definition (because the file is externally described). All you do is
recompile.

3-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Overriding externally defined data names


IBM i

• Assume externally described PayReg file has fields named:


– EmpNumber
– EmpLastNme
– EmpInitial
– EmpFrstNme
– EmpMonthRt
– EmpAddress
– :
• Using PREFIX(Pay:3) results in fields named:
– PayNumber
– PayLastNme
– PayInitial
– PayFrstNme
– PayMonthRt
– PayAddress
– :

© Copyright IBM Corporation 2002, 2014

Figure 3-19. Overriding externally defined data names AS068.1

Notes:
Notice that you need only to reference the file name and the record format that you want to define.
Also, using the keyword INCLUDE (or in contrast, IGNORE) saves you program storage space at
execution time as you are not defining any unused data in your program.
In this visual, you can also see the PREFIX keyword on the file spec. Using this keyword allows you
to prefix a variable name with the characters of your choice.
PREFIX allows global renaming of all fields in the file.
When you use PREFIX, you can concatenate characters to all field names and/or replace a specified
number of characters in all the original field names.
The PREFIX keyword of the File spec helps you to maintain uniqueness of the field names that you
use in your program. It does not change the names of the fields in your database files. These are
maintained the same as they were. However, the fields in your program override those names while
the program is executing and therefore, update any values that are changed in your program.
PREFIX can be used to replace a portion of the database field name or to concatenate a prefix to
them. Usually, we think that programmers will use the replace capability of the PREFIX keyword to
maintain the current length of their existing field names.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

To remove characters from the beginning of every name, specify an empty string as the first
parameter: PREFIX('':number_to_remove).
For example, PREFIX(‘‘:3) would remove the first three characters of every field name.
Characters used in your prefix can be specified as a name, for example PREFIX(F1_), or as a
character literal, for example PREFIX('F1_'). A character literal must be used if the prefix contains
a period; for example PREFIX('F1DS.') or PREFIX('F1DS.A').
You can still override field names specifically on your input specs (see the RPG IV Reference
manual for details). We suggest that you use the PREFIX keyword rather than using the override
capability on input specs. Thus, maintenance is easier.

3-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Like
IBM i

• Like: Length, decimal positions, and data type copied


• Increase (+) or decrease (-) length
• Use with fields, subfields

© Copyright IBM Corporation 2002, 2014

Figure 3-20. LIKE AS068.1

Notes:
The Like keyword copies the data type as well as the length and decimal positions of other fields.
Length adjustments can be done. The Like keyword is used to define an item similar to an existing
one. When the Like keyword is specified, the item being defined takes on the data type, length, and
the data format of the item specified as the parameter. Stand-alone fields and others can be defined
using this keyword. The parameter of Like can be a stand-alone field or certain other data types.
The data type entry (position 40) must be blank.
Note that the parameter of Like could be a field defined in an externally defined database. In this
situation, if the characteristics of the database field change, the field that is defined Like the
database field is changed also. Only recompilation of the program would be necessary. No lines of
program code would need to be changed.

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Machine exercise: Data definition


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 3-21. Machine exercise: Data definition AS068.1

Notes:
Perform the Data definition machine exercise.

3-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Checkpoint
IBM i

1. True or false: Named indicators are the preferred alternative


to numeric indicators as they allow you to use a meaningful
field name.

2. Data is defined in an RPG program with:


a. Input specifications and program described files
b. Externally described files
c. Definition specification definitions
d. All of the above

3. True or false: The Definition spec is NOT needed to define


fields from an externally described file.

© Copyright IBM Corporation 2002, 2014

Figure 3-22. Checkpoint AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 3. Data representation and definition 3-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit summary
IBM i

Having completed this unit, you should be able to:

• List the most common data types supported in RPG IV

• Use Definition specifications to define these data types

© Copyright IBM Corporation 2002, 2014

Figure 3-23. Unit summary AS068.1

Notes:
You have now learned the basics about how data is represented on the i and how you can access it
by using RPG IV programs.

3-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 4. Manipulating data in calculations

What this unit is about


In this unit, we discuss how you can operate on data in calculations using
free-format operation codes and expressions.
Conditional coding is introduced at this point as part of expressions.
One of the most important considerations when coding expressions is how to
determine the size of the numeric result of an expression. This is taught as a
part of this unit.
In addition, RPG IV’s rich set of compiler built-in functions are explained so
that you may use some of the more common ones to save valuable coding
time.

What you should be able to do


After completing this unit, you should be able to:
• Write calculation specifications using free form operation codes, and
expressions for:
- Assignment of numeric, character, and logical values
- Arithmetic operations
- Logical operations
- String handling operations
- Date manipulation operations
• Write built-in functions in expressions
• Determine the size of a numeric result field
• Use H-Spec keywords to manage the numeric result of an expression

How you will check your progress


• Machine exercises
• The students calculate a field's value using an expression (the program is
an enhancement to one of the earlier programs written in lab). Also,
calculate the final total.
• Given a report layout, the students write a new program using more
expressions to produce the desired results. During the lab, the students
write code for:
- Arithmetic and logical expressions
- String handling operations

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:


• Write calculation specifications using free-form operation
codes, and expressions for:
– Assignment of numeric, character, and logical values
– Arithmetic operations
– Logic operations
– String handling operations
– Date manipulation operations
• Write built-in functions in expressions
• Determine the size of a numeric result field
• Use control specification keywords to manage the numeric
result of an expression

© Copyright IBM Corporation 2002, 2014

Figure 4-1. Unit objectives AS068.1

Notes:

4-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Types of expressions
IBM i

• Assignment or data conversion


• Arithmetic
• Logical
• String

© Copyright IBM Corporation 2002, 2014

Figure 4-2. Types of expressions AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Assignment opcodes
IBM i

• Eval:
– Assignment using simple expression
– Result = Expression
– Supports all data types
– Data types must be compatible
– Left-justified with character operands
• EvalR: Same as Eval but:
– Character only
– Right-justified
• Eval-Corr:
– Move like named fields from one data structure to another

© Copyright IBM Corporation 2002, 2014

Figure 4-3. Assignment opcodes AS068.1

Notes:
The Eval and EvalR operation codes evaluate an assignment statement of the form
Eval Result = Expression. The expression is evaluated and the result placed in result. Therefore,
result cannot be a literal or constant but is an RPG IV field name. Eval is valid with both numeric
and character operands. Operand data types must be compatible.
EvalR is valid with character data only and, when used, right-justifies data.
Eval-corr is an efficient way to move data between data structures where the sub-fields have the
same names but may not be in the same order.
The Eval opcode does not need to be specified. It is recommended to not use it in free format
specifications.
Additional information
You see the Move opcodes used in legacy applications using fixed-format calculations. Move
opcodes are not supported in any free form calculations.

4-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty There are three Move opcodes. The Move opcode copies data from the field in factor2 to the result
field starting from the rightmost byte of factor2 to the rightmost byte of the result field.
C Move Factor2 Result
The MoveL opcode copies data from the field in factor2 to the result field starting with the leftmost
byte of factor2 to the leftmost byte of the result field. Data is moved a byte at a time and the
operation stops when there is no more data to be moved in factor2 or the result field cannot accept
any more data because it is full.
MoveA is the third opcode. It copies data to/from arrays. We discuss arrays on a subsequent unit.
So, the length of the shorter field determines how much data is moved. RPG IV does not clear the
result field before starting the Move operation. The data in the result field is overlaid by the data
from factor2. What this means is that data in the result field that is not affected by the Move (when
the result field is longer than factor2) is not changed. You can use the operation extender P (pad
with blanks) with the Move operation to clear the result field first.
We see examples of operation extenders in this unit.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Assignment of a numeric variable


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-4. Assignment of a numeric variable AS068.1

Notes:
A number of capabilities are introduced in this visual:
• The Eval opcode is implied in the expressions above. You can code the Eval using this form:
Eval NumericVar = 567;
• Numeric assignment using the Eval opcode (implicit).
• Clearing a numeric field using Eval. Notice the use of the constant 0, the figurative constant
*zero or *zeros.
• Clearing a numeric field using the Clear opcode. Clear resets the value of the numeric field to
its default initialization value of zero.
Rule of EVAL
The data types on the left and right of an expression must be compatible. For example, you cannot
assign a numeric variable to a character variable without having performed a conversion first.

4-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Assignment of a character variable


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-5. Assignment of a character variable AS068.1

Notes:
Note the ways that you can set the contents of a character field. Contrast the use of Eval versus
EvalR to set the field CharVar to "A_String", a character constant. Eval clears the result field and
left-justifies the data moved to the result. EvalR also clears the result field and right-justifies the
data.
A character field can be cleared in several different ways. Note the use of the constant ' ' and the
figurative constant *blanks.
You can also use the Clear opcode to initialize a character variable. Clear resets the value of a
character field to its default initialization value of blanks.
Eval-corr uses the variable name to move data between data structures. We will discuss data
structures and the qualified keyword more in a later unit.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Arithmetic operations
IBM i

2+2=4 25 = 32

4x2=8

SUM(5+4+9+10+16)

© Copyright IBM Corporation 2002, 2014

Figure 4-6. Arithmetic operations AS068.1

Notes:

4-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Arithmetic opcodes
IBM i

• Legacy opcodes:
– ADD
– SUB
– MULT
– DIV
– MVR
– XFOOT
– SQRT
– Z-ADD
– Z-SUB
• Best coded using Evals and BiFs
• Style tip:
– If there is a BiF, use it.
© Copyright IBM Corporation 2002, 2014

Figure 4-7. Arithmetic opcodes AS068.1

Notes:
These legacy operation codes are valid only with numeric fields, including numeric subfields,
parameters, arrays, individual array elements, table elements and numeric literals.
Legacy opcodes:
• ADD - addition of one field to another
• SUB - subtraction of one field from another
• MULT - multiply one field by another
• DIV - divide one field by another
• MVR - move the remainder following a divide into a field
• XFOOT - crossfoot a set of fields (elements) in an array
• SQRT - calculate the square root of a field
• Z-ADD - zero the result field and add the value of another into the result
• Z-SUB - zero the result field and subtract the value of another into the result

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

The i preferred numeric format is packed data. This means that the system converts all numeric
data to be operated on into packed decimal before operating on it. Then, the system converts it
back to its original format when done. Remember this when you are building databases that define
numeric data.
The sign of the result field is determined algebraically and is set to an F if positive and to a D if
negative.
An RPG IV numeric Packed or Zoned Decimal field can be a maximum of 63 digits (V5R3; prior
releases maximum is 30 digits) in length. The limits for other numeric data types are:
Binary - 4 or 9 digits
Integer - +/- 3, 5, 10 or 20 digits
Unsigned - +3, 5, 10 or 20 digits
Remember to define your result fields with adequate length and decimal places (precision) for the
calculation.
The Xfoot (crossfoot) opcode sums are a set of numeric data stored in an array. Crossfooting is
discussed in the Using arrays, data structures, and data areas unit later in the course.
It is important for you to be aware of the legacy operation codes. In this class, we do not spend any
time using them. We use Eval and Built In functions throughout the class.
If there is a built-in function and an opcode that do the same thing, it is preferred to use the BiF as it
tends to be more efficient as well as allow you to stay in free form.
References:
ILE RPG Language Reference, Operation, Expressions, and Functions

4-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Addition and subtraction


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-8. Addition and subtraction AS068.1

Notes:
Note that the use of free-format coding (implicit Eval) makes your program very easy to read and
understand.
In the lower portion of the visual, notice two unary operations. They reduce the number of
keystrokes required when compared to the statements above them. Reaction to these unary
operations has been mixed as they tend to make the purpose of the statement less clear than if the
complete expression is coded.
These are all the unary operations:
+=
-=
*=
/=
**=
Notice that when you use short form, the operator must be coded with no blanks. For example, +=
is correct, but + = (with a space in between) will generate an error.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Multiplication
IBM i

• When using operation extender, Eval must be explicit.

© Copyright IBM Corporation 2002, 2014

Figure 4-9. Multiplication AS068.1

Notes:
These are several simple calculations to show you how to perform multiplication. They also show
that you must make sure that your result field is large enough to hold both the whole number and
the decimal result of your calculations.
The H is known as an operation extender. The H operation extender rounds up the arithmetic
result and then places it in the result field.
When you code the H or any other operation extender for an expression, you must code the Eval
explicitly. If no extender is wanted, you may omit the Eval as it is implied in the free format
statement.
But, there is a problem with the last line of code. While it is valid format, when executed, you would
get an execution-time error like this:
RPG procedure performed an arithmetic operation that resulted in a value that is too
large to fit in the target. If this is a numeric expression, the overflow could be the result
of the calculation of some intermediate result.
Result3 is 5 digits with three positions before the decimal and two reserved for decimal places. The
value calculated, 1234.66, requires four positions before the decimal. An error condition results.

4-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Numeric overflow
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-10. Numeric overflow AS068.1

Notes:
When numeric overflow occurs in a free-form expression, a runtime error occurs. In order to avoid
this problem, you should determine adequate field sizes for every field that is the result of an
accumulation or multiplication using the following guidelines:
• Addition
The result field should be one digit larger to the left of the decimal than the larger field in the
expression.
Example:

FldA is (4 2), that is, 99.99 (max. value)


FldB is (5 2), that is, 999.99 (max. value)

FldC = FldA + FldB (FldC = 1099.98)

Define FldC as (6 2) in order that it can hold 9999.99

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

• Multiplication
The result field should be two digits larger to the left of the decimal than the largest field in the
operation.
Example:

FldA is (4 2)
FldB is (5 2)

FldC = FldA * FldB

Define FldC as (7 2) in order that it can hold 99999.99

Note
When your expressions include fields of different decimal positions, the rightmost digits are
truncated based on the number of decimal positions defined for your result field that contain the
new value. You may round up using the half adjustment feature of RPG IV, the H operation
extender.
In the ILE RPG for i Reference, read about the TRUNCNBR option of the RPG IV compile
commands. It is also a keyword on the control spec. TRUNCNBR specifies whether the truncated
value is moved to the result field or an error is generated when numeric overflow occurs while
running the program.
TRUNCNBR does not apply to calculations performed within expressions. If any overflow occurs
within expressions calculations, a runtime message is issued.
In addition, TRUNCNBR does not apply to any arithmetic operations performed in integer or
unsigned format.

4-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Division and remainders


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-11. Division and remainders AS068.1

Notes:
Free-form division is done using the familiar slash (/) character. The use of the H operation extender
(half adjust) rounds up the result of the calculation before placing it in the result field.
In this visual, notice the code with the %Div and %Rem. These are known as Built-in functions or
simply, BiFs. BiFs are included in the RPG IV compiler. We will be using them throughout the
course.
Notice that you pass parameters to BiFs. Parameters are enclosed in parentheses and are
separated by a colon when two or more parameters are passed. A BiF returns a specific value
when it is evaluated.
The two BiFs in this example:
• %Div expects two parameters, where the first is divided by the second. This BiF returns the
integer result of the division.
• %Rem expects two parameters, where the first is divided by the second. This BiF returns the
remainder of the division as an integer.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Here are some further notes about the visual. The notes are based on the reference numbers in the
figure:
1. We know that 200/3 = 66.66666667 depending on how many decimal places you want to carry.
In this example, we are not rounding and we carry only two decimal places. Therefore the result
of the division is 66.66 and the corresponding remainder is 000.02.
2. In this example, we use rounding and still carry two decimals. Therefore, the result of the
division is 66.67 and the remainder is -000.01 (66.67*3 = 200.01).
3. %Div and %Rem are handy tools but they return only integer values.
4. When you attempt to code an expression in this way, you must always be aware of what are
called intermediate results. These have a dramatic influence on your final result because of the
precision rules. We discuss them later.
5. Again, note that %Div returns an integer result. No fractions are returned.
6. This is a more accurate way of determining the remainder, but we are still limited to an integer
result. Notice the use of nesting of functions. We will see more of this later.
7. This is another example of division. Because Years has no decimal places, Months / 12 returns
the same result as %Div(Months : 12).

4-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Coding BiFs
IBM i

• Coding syntax:
– %function-name{(argument{:argument...})}
• Arguments can be:
– Variables
– Constants
– Expressions
– Prototyped procedure
– BiFs
• Examples:
– %Div(200 : 3)
– %Rem(200 : 3)
– %Eof(EmpMaster)
– %TrimL('? *' : String)

© Copyright IBM Corporation 2002, 2014

Figure 4-12. Coding BiFs AS068.1

Notes:
Built-in functions (BiFs) add tremendous function to the RPG IV language. All built-in functions have
the percent symbol (%) as their first character. The syntax of built-in functions is:

%function-name{(argument{:argument...})}

Arguments for the function may be variables, constants, expressions, a prototyped procedure, or
other built-in functions. (Procedures are covered on a subsequent course.)
An expression argument can include a built-in function. BiFs can be nested and works if the result
of the nested BiF produces a valid parameter for the outer BiF.
BiFs can be used on the Definition spec, Calculation spec in expressions or in free-format
calculations. They cannot be used with legacy fixed-format opcodes.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Exponentiation
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-13. Exponentiation AS068.1

Notes:
This visual illustrates how the Eval (in explicit and implicit forms) opcode is able to perform
exponentiation. Exponentiation can be used to extract square and cube roots, for example.

4-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Machine exercise: Adding arithmetic functions


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-14. Machine exercise: Adding arithmetic functions AS068.1

Notes:
Perform the machine exercise Adding Arithmetic functions.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Comparison operations
IBM i

• x=y • Equality
• x <> y • Not equal
• x>y • Greater than
• x >= y • Greater than or equal
• x<y • Less than
• x <= y • Less than or equal
• x AND y • Logical and
• x OR y • Logical or
• NOT y • Logical not

© Copyright IBM Corporation 2002, 2014

Figure 4-15. Comparison operations AS068.1

Notes:
These operations are valid in expressions in RPG IV:
= The equality operation returns 1 if the two operands are equal, and 0
if not equal.
<> The not equal (inequality) operation returns 0 if the two operands are
equal, and 1 if not equal.
> The greater than operation returns 1 if the first operand is greater
than the second.
>= The greater than or equal operation returns 1 if the first operand is
greater or equal to the second.
< The less than operation returns 1 if the first operand is less than the
second.
<= The less than or equal operation returns 1 if the first operand is less
or equal to the second.

4-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty AND The logical and operation returns 1 if both operands return a value of
the indicator operand of 1.
OR The logical or operation returns 1 if either operand returns a value of
the indicator operand of 1.
NOT The logical not operation is used with an indicator operand. It returns
1 if the value of the indicator operand is 0 and 0 if the indicator
operand is 1.
Expressions are used not only with the Eval operation code, but also with conditional opcodes. We
introduce the If opcode in this topic and cover other conditional opcodes in the Structured
Programming, error handling, subprocedures, and subroutines unit.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Class exercise
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-16. Class exercise AS068.1

Notes:
Indicator1 and Indicator2 are defined as named indicators. Write an explanation that describes
what is being done by each of the statements above:
1
____________________________________________________________
2
____________________________________________________________
3
____________________________________________________________
4
____________________________________________________________
5
____________________________________________________________

4-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

If/Else/EndIf
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-17. If/Else/EndIf AS068.1

Notes:
The If operation code allows a series of calculations that follow it to be processed if a condition is
met. The logical condition is expressed by an indicator-valued expression (the result of the test of
the expression is a 1 or a 0). The operations controlled by the If operations are performed when the
expression in the extended factor 2 field is true.
If statements are coded including an expression, such as those shown in this visual.
The rules for the comparison of an expression in the If are the same as they are for any
comparison. The fields must be the same type. Each If is delimited by an End or EndIf. If the result
of the If is true, then the code before the Else is executed. If the comparison is false, the code
between the If and the Else is skipped and the code after the Else is executed.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

If expressions
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-18. If expressions AS068.1

Notes:
Note not only the use of a conditional expression with the If operation, but also that each If is
matched with an EndIf.

4-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Using Do While (DoW)


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-19. Using Do While (DoW) AS068.1

Notes:
Use Do loops to perform calculations that are to be repeated when a certain condition is true. One
of the most commonly used forms of Do is the DoW operation code. The logic between the DoW (2)
and the EndDo (5) is performed when the expression to the right of the DoW is true. For this form of
Do, the expression is tested before the logic is performed.
In this example, notice that we first perform a read of the Item_PF file. The reason we do this is to
find out whether there are any records in the file. In the DoW (2), notice that the expression tests for
end of file using the %Eof Built-in function.
In the loop, we process each record (3), starting with the first one (which we have already read).
Then, we read the second through the last records (4). Once we reach end of file, we drop out
of the loop and end the program (5).

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

String handling
IBM i

S T R I N G
P
G

P R O G R A M M I N G

P R O G R A M

© Copyright IBM Corporation 2002, 2014

Figure 4-20. String handling AS068.1

Notes:
A common programming task is to manipulate character string data. RPG IV offers a number of
features to make this simple for you to code and read when you are maintaining existing code.

4-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

String handling BiFs


IBM i

BiF Purpose
%Char Convert to character
%Dec Convert to decimal
%Int Convert to integer
%EditC Edit numeric using edit code
%EditW Edit numeric using edit work
%Replace Replaces all or part of character string
%ScanRpl Scan/replace search argument against character string
%Subst Extracts substring from a character string
%Trim Removes left and right characters from a string
%TrimL Removes left characters from a string
%TrimR Removes right characters from a string

© Copyright IBM Corporation 2002, 2014

Figure 4-21. String handling BiFs AS068.1

Notes:
Built-In Functions (BiFs) are IBM-supplied routines that perform many popular functions.
IBM-supplied BiFs always start with the % character.
In this topic, we explain some of the BiFs that perform string handling. Other BiFs are discussed as
we encounter them in later topics.
References:
ILE RPG for Language Reference, Operations, expressions, and functions, Built in functions

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Concatenation
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-22. Concatenation AS068.1

Notes:
Notice that the (implicit) Eval opcode does not strip any blank characters from the result field. It
simply concatenates strings.
Notice that the fields FirstName and LastName are each six characters in length. Each field's initial
value is padded on the right with one or more blanks.
Question: In the last example, can you explain why the blank after ‘Smith’ in LastName is
truncated?

4-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Remove characters: %Trim


IBM i

%Trim(string:{chars}) %TrimL(string:{chars})
%TrimR(string:{chars})
• %Trim strips leading and trailing characters from a string (default
blanks)
• %TrimL strips leading characters only (default blanks)
• %TrimR strips trailing characters only (default blanks)

© Copyright IBM Corporation 2002, 2014

Figure 4-23. Remove characters: %Trim AS068.1

Notes:
The Trimx built-in functions allow you to strip characters from the beginning and/or end of a
character variable. Note that the results can be used wherever a character field can be used,
including in a string manipulation expression, as in the example.
The characters to be stripped are defined as an optional second argument. If the second argument
is not specified, blanks are assumed.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Length and size of a string: %Len and %Size


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-24. Length and size of a string: %Len and %Size AS068.1

Notes:
In the second example, we strip trailing blanks using %TrimR and use %Len to determine the
length of the trimmed string. %Len is not sensitive to any blanks in the middle of the string value.
Then, we contrast the use of %Len and %Size. Whereas %Size returns the allocated size of a field
as a number of bytes, %Len returns the declared length of a field as a number of characters or
digits.

4-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Scan for character string: %Scan


IBM i

%SCAN(search argument : source string {: start})

© Copyright IBM Corporation 2002, 2014

Figure 4-25. Scan for character string: %Scan AS068.1

Notes:
%Scan returns the first position of the search argument in the source string where the search string
was found, or 0 if it was not found. If the start position is specified, the search begins at the starting
position. The result is always the position in the source string even if the starting position is
specified. The starting position defaults to 1.
The search argument (first parameter) must be either a character (or a graphic) data type. The
search string (second parameter) must be the same data type as the search argument. The starting
position of the search (third parameter), if specified, must be numeric with zero decimal positions.
The data type of the return value is unsigned integer. This built-in function can be used anywhere
that an unsigned integer expression is valid.
Note that the search argument used is compared in its complete form with the string to be scanned.
If you do wanted to ignore leading and trailing blanks, you could use %Trim to remove all unwanted
blanks as shown in the last example.
The %Scan BiF is case-sensitive.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Scan and replace for character string: %ScanRpl


IBM i

%ScanRpl(search argument : replacement string :


source string {: start} {:length})

© Copyright IBM Corporation 2002, 2014

Figure 4-26. Scan and replace for character string: %ScanRpl AS068.1

Notes:
%ScanRpl returns the string produced by replacing all occurrences of the search argument in the
source string with the replacement string. The search for the search argument starts at the scan
start position and continues for the scan length. The parts of the source string that are outside the
range specified by the scan start position and the scan length are included in the result.
The first, second and third parameters must be character, graphic, or UCS-2 data types. They can
be in either fixed-length or variable-length format. These parameters must all be of the same type
and CCSID.
The fourth parameter represents the scan starting position, measured in characters, where the
search for the scan string should begin. If it is not specified, the starting position defaults to one.
The value may range from one to the current length of the source string.
The fifth parameter represents the number of characters in the source string to be scanned. If the
parameter is not specified, the length defaults to the remainder of the source string starting from the
start position. The value must be greater than or equal to zero, and less than or equal to the
remaining length of the source string starting at the start position.

4-32 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty The starting position and length may be any numeric value or numeric expression with no decimal
positions.
The returned value may be larger, equal to or smaller than the source string. The resulting length
depends on the lengths of the scan string and the replacement string, and also on the number of
times the replacement is performed. For example, assume the scan string is 'a' and the
replacement string is 'bc'. If the source string is 'ada', the returned value has a length of five
('bcdbc'). If the source string is 'ddd', the returned value has a length of three ('ddd').
The returned value is varying length if the source string and replacement string have different
lengths, or if any of the strings are varying length. Otherwise, the returned value is fixed length. The
returned value has the same type as the source string.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Extract substring: %Subst


IBM i

%SUBST(string:start{:length})

© Copyright IBM Corporation 2002, 2014

Figure 4-27. Extract substring: %Subst AS068.1

Notes:
The substring built-in function allows you to extract a substring from a field. The first parameter is
the field upon which the operation is to be performed. The parameter after the field name, delimited
by a colon, is the starting position of this field where the operation is to begin. The last parameter,
which is optional, is the length of the string. The length parameter represents the length of the
substring.
If it is not specified, the length is the length of the string less the start value plus one. For example,
if the operation is to take place on a 15 byte string, starting in the fifth position, the length of the
substring is assumed to be 11 characters.
Note that in the final Eval in this visual, the previously calculated value of FirstName field could
have been used rather than substringing the NameField again. We could have written:
ReverseNm = %TrimR(%Subst(NameField : BlankPos + 1))
+ ', ' + FirstName

4-34 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Replace string of characters: %Replace


IBM i

%REPLACE(replacement string: source string(:start position


{:source length to replace}})

© Copyright IBM Corporation 2002, 2014

Figure 4-28. Replace string of characters: %Replace AS068.1

Notes:
The %Replace BiF replaces a specified number of characters in one string with characters from
another. The parameters are:
1. Replacement string
2. Source string
3. Start position
4. Number of positions to replace
This example illustrates the function of %Replace. We are using a generic greeting message to
wish someone a Happy Birthday. The %Replace BiF is used to replace the characters, with a
person’s name.
To do this, we should handle some other details in addition to the replacement:
1. Check to make sure that the string we expect to replace in the string is in the string and is &C.
To do this, we use the %Scan BiF to find the starting position of the &C substring.
2. If the starting position is greater than zero, we perform the replacement operation using the
%Replace BiF.
3. We also use the %trim BiF to remove any leading and trailing blanks in the FullName string
that will replace the &C characters.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Convert to character: %Char


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-29. Convert to character: %Char AS068.1

Notes:
Remember that the Eval requires that all variables operated on the statement must be the same
data type. In this example, we want to derive an edited character field based on three numeric
fields.
Because PhoneNumber is a character field, all fields in the expression to the right of the = sign
must be character and we use the %Char BiF to convert the numeric values to character.
The %char BiF can operate on various data types, including graphic, UCS-2, numeric, date, time or
timestamp data types. The converted value remains unchanged but is returned in a format that is
compatible with character data.

4-36 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Edit with %EditC or %EditW


IBM i

%EDITC(numeric : editcode {: *ASTFILL | *CURSYM | currency-


symbol})

%EDITW(numeric : editword)

© Copyright IBM Corporation 2002, 2014

Figure 4-30. Edit with %EditC or %EditW AS068.1

Notes:
%EditC and %EditW BIFs are very useful in the conversion of a numeric value to an edited
character value.
%EditC edits a numeric field, producing a character value; it expects two (optionally three)
parameters:
1. Numeric
2. Edit Code
3. *cursym|*astfill|currency-symbol (optional)
This parameter can optionally provide asterisk fill, a floating system currency symbol, or a specified
floating currency symbol.
%EditW edits a numeric field, producing a character value; it expects two parameters:
1. Numeric
2. Editword
The edit word can be supplied as a literal value or as a constant shown in the example.
We cover more of the available edit codes available in RPG IV in the next unit, Using device files.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

References:
IBM i Information Center: Programming DDS for Printer Files, Keyword Entries for Printer Files

4-38 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Convert to numeric: %Int and %Dec


IBM i

%Int(expression)
%Dec(expression:{precision:decimal places})

© Copyright IBM Corporation 2002, 2014

Figure 4-31. Convert to numeric: %Int and %Dec AS068.1

Notes:
%Int converts the numeric or character expression to a signed integer. Any decimal digits are
truncated.
%Dec converts the value of the numeric or character expression to decimal (packed) format with
precision digits and decimal places. Precision and decimal places must be numeric literals, named
constants that represent numeric literals, or built-in functions with a numeric value known at compile
time.
The arguments precision and decimal places may be omitted if the type of expression is not float or
character. If these arguments are omitted, the precision and decimal places are taken from the
attributes of numeric expression.
In the examples above, blanks, a comma, a period, a -sign and a +sign are permitted. A comma is
interpreted as a decimal point.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-39
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Convert string: %Xlate


IBM i

%Xlate(from:to:string{:startpos})

© Copyright IBM Corporation 2002, 2014

Figure 4-32. Convert string: %Xlate AS068.1

Notes:
%Xlate translates a string according to the values of from, to, and startpos.
1. The first parameter contains a list of characters that should be replaced.
2. The second parameter contains their replacements. For example, if the string contains the third
character in from, every occurrence of that character is replaced with the third character in to.
3. The third parameter is the string to be translated. The fourth parameter is the starting position
for translation. By default, translation starts at position 1.
4. The fourth parameter is a numeric variable or value (not floating point) with zero decimal
positions for the starting position of the operation.
The first three parameters can be of type character, graphic, or UCS-2. All three must be the same
data type. The value returned has the same type and length as string.
The first example in this visual shows the character " " being replaced by a hyphen. The second
example shows the replacement of the lowercase characters, "iv", by the uppercase characters,
"IV".

4-40 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Date/Time/TimeStamps: Testing for valid dates


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-33. Date/Time/TimeStamps: Testing for valid dates AS068.1

Notes:
You test for a zero divisor before you perform a division to avoid a divide by zero error.
You should also test fields that are moved to Date, Time, or TimeStamp fields before you perform
the operation. To test for a valid Date, Time, or TimeStamp value use the TEST opcode with an
extension of D, T, or Z. The result field might be a Date, Time, TimeStamp, or a Numeric field. You
must use the E-extender and the %error BiF (%error not shown).
%Error is turned off if the Date/Time/TimeStamp is valid. Factor 1 defines the result field format.
Look at the line of code:
TEST(DE) *YMD CharDate;
What separator is being checked for in this code, / or &? The answer is / since this is the default
separator for the *YMD format. Any control spec format does not apply.
Character or numeric fields can be tested to see if they contain a valid Date, Time, or TimeStamp.
The purpose of this would be to avoid getting an error on a move to a date or time field, typically. If
you are unsure of the format of the date in a character or numeric field, you could test for various
formats.
Also, Date, Time, and TimeStamp fields can be tested for valid values.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-41
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Moving to and from date and time fields


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-34. Moving to and from date and time fields AS068.1

Notes:
1. UpdDate the assignment is direct as Date1 is a date variable.
2. UpdTime the assignment is direct as Time1 is a time variable.
(It is never necessary to specify a format for a TimeStamp because there is only one format
available.)
We know from the INZ value set in the Definition spec that we have valid values. But, never
forget the importance of testing the value before attempting the Eval operation. If the character
field contained invalid date data (including blanks or zeros), the assignment to the date data
type fails.
3. Converts from one date format to another date format.
4. Converts from a numeric field to a date field. You should specify the date format of the numeric
or character variable to be converted. If you do not specify a format, the default value is either
the format specified on the control spec DatFmt keyword or *ISO (control spec default).
5. Converts a date to a character field.
6. Converts from the date the program was run to a character field.

4-42 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty 7. One method of converting a date to a numeric is using the %Subdt BiF that takes a portion of
the date. %Subdt returns a numeric value.
8. An easier method is to move a date to a character field and overlay the character field with a
zoned numeric field.
9. You can also use the %INT BiF with the %CHAR BiF to do the conversion. The system will have
to internally convert from integer to zoned. %INT can’t handle a date field directly.
10. 10 You can use the %DEC BiF without needing to first convert to character.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-43
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Date and time durations


IBM i

• Possibilities:

*YEARS *Y
*MONTHS *M
*DAYS *D
OR
*HOURS *H
*MINUTES *MN
*SECONDS *S
*MSECONDS *MS

• Specify as subfactor in factor 2 or result field


• Use as parameter with %Diff and %SubDt BIFs
© Copyright IBM Corporation 2002, 2014

Figure 4-35. Date and time durations AS068.1

Notes:
This visual summarizes how you specify the duration is to be expressed. We cover some examples
in the visual that follows.
Durations can be determined or used in the %Diff BiF. They can be added to or subtracted from
date, time, or timestamp fields. They can be the result of adding or subtracting from two date, time,
or timestamp fields.
The %SubDt BiF is used to extract a portion of a date, time, or timestamp.

4-44 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Duration considerations
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-36. Duration considerations AS068.1

Notes:
When you calculate durations, the results might differ from your expectations.
The above code illustrates the results of several duration calculations.
Following the addition of one month to January 30, 2000, the resulting value in NewDate is
02/29/2000. This is because February 30, 2000, is an invalid date value. Because 2000 is a leap
year, the day is set to the last day of February 2000, which is 29.
Following the subtraction of one year from NewDate (which contains 02/29/2000 from the step
above) the value in NewDate becomes 02/28/1999. Similar to the case above, the subtraction of a
year from 2000 without changing the resulting day results in an invalid date value. So the day value
was set to the last valid day of February in 1999.
Following the subtraction of one month from May 31, 1999, the resulting value in NewDate will be
04/30/1999.
The results of duration calculations such as these may produce interesting results. However, the
results of these situations are quite predictable and accurate. Doing similar duration calculations on
date fields using the SQL language, for example, produces similar results.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-45
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

While the duration BiFs (%Diff and %Years, and so on) are easy to use and very powerful, there
are some limitations that are described as unexpected results in the RPG Reference manual. The
above code illustrates the unexpected results of a duration calculation.
References:
ILE RPG Reference Manual, Operations, Expressions, and Functions. Operations - Date
Operations

4-46 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Precedence rules
IBM i

1. ()
2. Built-in functions
3. Negation (-,NOT)
4. ** Exponentiation
5. *,/ Multiplication and division
6. +,- Addition and subtraction
7. =,> =,>, <=, <, <> Comparison
8. AND
9. OR
Result=A + B * C ** (X * Y)

If A=3, B=4, C=5, X=1, Y=2, what will be the value of the Result?
© Copyright IBM Corporation 2002, 2014

Figure 4-37. Precedence rules AS068.1

Notes:
When using expressions, precedence rules are used to determine the order of evaluation of the
parts of the expression. These precedence rules are similar to the traditional rules in arithmetic
expression elsewhere.
The most important point to note here is that parentheses have the highest precedence and
therefore can be used to ensure correct results, as well as to make the expression more readable.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-47
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Precedence rules: Using parentheses


IBM i

( ) are highest in precedence; use them to:


• Break up complex expressions
• Ensure accurate results

© Copyright IBM Corporation 2002, 2014

Figure 4-38. Precedence rules: Using parentheses AS068.1

Notes:
It is strongly recommended that you use parentheses frequently and freely, not only to ensure
correct calculation results, but also to make the code easier to read and understand, without
requiring the reader to go through the precedence rules to understand the expression.
The use of parentheses makes the code less ambiguous to the programmer, and therefore,
maintenance is not only easier to perform, but more reliable.

4-48 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Precision: Expressions
IBM i

Expected value of mark up percentage is 33.33.

© Copyright IBM Corporation 2002, 2014

Figure 4-39. Precision: Expressions AS068.1

Notes:
Developers have always been responsible for ensuring accurate results of calculations in their
programs. When coding expressions that are complex, it is important to test your code carefully to
ensure that the calculations produce the correct results.
Precision is important when you have an expression that has intermediate results. It is these
intermediate results that can affect the accuracy of your final result, particularly when you have
multiple division operations and/or division involving integer variables or literals (zero decimals).
Precision rules state that:
• Intermediate integer or unsigned results have a precision of 10 digits.
• Precision rules do not affect floating point data, which has the precision of double precision
floating point data.
The rules of precision as they apply to the intermediate results of expressions are described in the i
ILE RPG Language Manual. You should become familiar with them. Please review the pages
containing the precision rules and formulae in the RPG Reference manual.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-49
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Note that the TRUNCNBR option of the CRTBNDRPG or the CRTRPGMOD commands does not
apply to calculations performed within expressions. If overflow occurs during an operation involving
expressions, a runtime message is issued.
References:
ILE RPG Language Reference, Operations, Expressions, and functions, Expressions

4-50 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Specifying precision rules


IBM i

• Resulting decimal positions:


– ResDecPos on control specification applies to all Evals
– R-extender without *ResDecPos applies to single Eval

© Copyright IBM Corporation 2002, 2014

Figure 4-40. Specifying precision rules AS068.1

Notes:
The simplest way to control the precision of the results of expressions is to base them on
the number of decimal positions of the result field. Result Decimal Position Precision Rules
mean that the decimal accuracy you want in the result field of the expression determines the
decimal accuracy that the system must carry for Intermediate Results or Subexpressions.
The ExPrOpts (expression options) keyword specifies the type of precision rules to be used for an
entire program. If not specified, you experience results that may not make sense.
If ExPrOpts is specified, with *ResDecPos, the Result Decimal Position precision rules apply and
force intermediate results in expressions to have no fewer decimal positions than the result.
ResDecPos
At this point in your RPG IV training, you should always code the ExPrOpts(*ResDecPos) keyword
and parameter on the control spec.

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-51
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Machine exercise: Data manipulation


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 4-41. Machine exercise: Data manipulation AS068.1

Notes:
Perform the machine exercise Data manipulation.

4-52 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Checkpoint
IBM i

1. Given the following values for the variables, what will be the
value of X after the Eval statement?
A = 1, B = 2, C = 3
Eval X = A * B + C ** B - 1

2. Given the same initial values for the variables A, B, and C,


what will be the value of X after this Eval statement?
Eval X = A * B + C ** (B – 1)

3. Given the same initial values for the variables A, B, and C,


and given that *IN03 is *ON, what will be the value of *INLR
after this Eval statement?
Eval *INLR = *IN03 AND B > A OR C > A + B

© Copyright IBM Corporation 2002, 2014

Figure 4-42. Checkpoint AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 4. Manipulating data in calculations 4-53
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit summary
IBM i

Having completed this unit, you should be able to:


• Write calculation specifications using free-form operation
codes, and expressions for:
– Assignment of numeric, character, and logical values
– Arithmetic operations
– Logic operations
– String handling operations
– Date manipulation operations
• Write built-in functions in expressions
• Determine the size of a numeric result field
• Use control specification keywords to manage the numeric
result of an expression

© Copyright IBM Corporation 2002, 2014

Figure 4-43. Unit summary AS068.1

Notes:

4-54 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 5. Using printer and display files in an RPG
IV program

What this unit is about


This unit describes how to use externally described DDS to produce printed
output from an RPG IV program. First, this unit briefly reviews the creation of
printer DDS and discuss how it can be used within an RPG IV program.
This unit reviews some concepts taught in OL49/OL490, a prerequisite for
this class. What is new in this unit is the actual design of a report, the
entering of the DDS to describe the printer file (PRTF), creating a printer file,
and writing to the printer file from your RPG IV program.

What you should be able to do


After completing this unit, you should be able to:
• Use DDS to define the layout of a report
• Create a printer file (PRTF)
• Write an RPG IV program that prints a report using a printer file defined in
DDS
• Describe the properties of a display file
• Create display files using DDS
• Use Exfmt and write RPG IV operation codes with display files
• Code inquiry RPG IV programs to support one display file

How you will check your progress


• Checkpoint questions
• Machine exercise:
• Given a problem statement, the students create a printer file to format the
data into detailed line items and a grand total. Then, the students code
the program that prints the report using the externally described printer
file. During this exercise, the student:
- Creates a printer file with DDS incorporating:
• Database fields
• Programmer described fields
• EDTCDE, SKIP, SPACE, PAGE, DATE, TIME keywords
• Writes RPG IV code to use an externally described printer file and
handle page overflow

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:


• Use DDS to define the layout of a report
• Create a printer file (PRTF)
• Write an RPG IV program that prints a report using a printer
file defined in DDS
• Describe the properties of a display file
• Create display files using DDS
• Use Exfmt and write RPG IV operation codes with display files
• Write inquiry RPG IV programs to support one display file

© Copyright IBM Corporation 2002, 2014

Figure 5-1. Unit objectives AS068.1

Notes:

5-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Printing process
IBM i

Program
Output to Output
printer queue
Spooled
file
file
Entry
Printer file

SPOOL(*YES)

OUTQ
( )*JOB
name

Printer writer
(IBM-supplied)
© Copyright IBM Corporation 2002, 2014

Figure 5-2. Printing process AS068.1

Notes:
This is the process followed for printing:
1. RPG program plus printer file produce report
2. Printer file specifies *SPOOL=*YES
3. Spool file created
4. Spool file entry placed in OUTQ
5. Print writer uses OUTQ entry to move spool file to printer device
6. Physical printer produces report
When a user runs a program, its associated printer file is accessed, a spooled file member is
generated and placed in the system spool file (in library QSPL). An entry is placed in an output
queue that points to the spool file member. Now, we discuss the relationship between printer files,
spooled files, and output queues.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Printer files
Printers attached to the i system are supported by the operating system through device
descriptions. Printer files describe how the system operates on the data when the report is created
by your application and eventually sent to a printer.
Every request for printing is handled by a printer file. You can create your own printer files using the
create printer file (CRTPRTF) command or you can use system-provided printer files.
Printer files contain many parameters that tell the system how the output should be formatted, what
font to use for the printed output, whether to print on both sides of the page, and more. The
parameters that control how your output is handled and where it goes are:
• Spool the data (SPOOL)
• Device (DEV)
• Spooled output queue (OUTQ)
Simultaneous peripheral operations online
Almost all application programs that generate printed output make use of the spooling support
provided with the i system. Whether spooling support is requested is determined by specifying
SPOOL=*YES or SPOOL=*NO on the SPOOL parameter of a printer file command (CRTPRTF).
By creating and using your own printer file instead of using a system-supplied printer file, you can
specify the printing control instructions that your application program receives.
You can use the create printer file (CRTPRTF) command to create your own printer file.
Output queues
Output queues are objects, defined to the system, that contains queued entries that point to
spooled files waiting to be printed. Output queues are created by the user or by the system.

5-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Printing elements
IBM i

• Spooled file
• Output queue
• Printer writer
• Print devices
• Printer files
• Job description
• Workstation description
• User profile
• System values

© Copyright IBM Corporation 2002, 2014

Figure 5-3. Printing elements AS068.1

Notes:
Element and definition
Spooled file: This is a file that holds output data waiting to be printed. The spool file is created by
IBM i (i5/OS), and, there is usually only one such file in QSPL library. It is the spool file MEMBER
that is added when a printout is generated from a printer file. A spooled file member is created by
an i (i5/OS) system program, an application program, or the Print key being pressed.
Output queue: An output queue is an i object that contains entries pointing to spooled files waiting
to be printed. Output queues can receive spooled files from more than one application program and
from more than one user.
Printer writer: This is a function of the operating system that sends the spooled file from an output
queue to a printer. In most cases, the application program sends the spooled file to an output queue
first. Then the printer writer program sends it to a printer.
Print devices: Printer devices are the physical printers that can be attached to the i system. Print
devices (printers) should not be confused with the printer writer program or printer files.
Printer files: Printer files describe how the system is to operate on data that passes between your
program and a printer. A printer file has many parameters. The spooling parameter (SPOOL)

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

determines if your output goes to an output queue or directly to a printer. The device (DEV)
parameter is the name of the printer your output is printed on. The output queue (OUTQ) parameter
is the name of the output queue your spooled files are sent to.
Job description: A job description is a system object that defines how a job is to be processed. A
job description has many parameters. Printer device (PRTDEV) and output queue (OUTQ) are the two
parameters that help determine where your output goes.
Workstation description: The workstation description contains information collected from the
device description for the display. Two of the device description parameters, printer device (PRTDEV)
and output queue (OUTQ), help determine where your output goes.
User profile: This object with a unique name contains the user's password, the list of special
authorities assigned to a user and the objects the user owns. A user profile has many parameters.
Printer device (PRTDEV) and output queue (OUTQ) are the two parameters that help determine where
your output goes.
System values: System values control information for the operation of certain parts of the system.
System administrators maintain system values to define the overall system working environment.
The system value most important to printing is the default system printer.

5-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Elements that control printing


IBM i

Output queue
1

Printer file
SMITH 3
Job description
User profile
- TAX97
Workstation description
- DEDUCT
- GROSS
System value

JONES

- INVOICES
2
- SALES
Printer writer
program
(system-supplied)

© Copyright IBM Corporation 2002, 2014

Figure 5-4. Elements that control printing AS068.1

Notes:
Moving your printed output from your program to a specific printer device involves many different
elements.
This visual illustrates how these elements that control printing are interrelated. To produce printed
output, the attributes that are common to all the elements (output queues and printer devices) must
be correctly matched.
Spooled files and output queues are identified by 1 in the visual. Your program writes report
(printed) output as spool files to an OUTQ.
Elements that control or direct the printing activity are:
• The printer writer program is identified by 2 in the visual. The print writer is the software that
starts or stops the systems interface to a specific printer device. When the printer is started,
spool files may be moved from the OUTQ to the print device.
• Printer files, job descriptions, user profiles, workstation descriptions, and system values are
identified by 3 in the visual. The objects control how the output is printed, what OUTQ is used,
and so on.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

For those who are unfamiliar with spooling, here are a few benefits of using spooling:
• Releases the application from the (slow) printer device
• Drives the physical printing by a separate batch job (the spool writer)
• Allows better utilization of resources
• Allows the same device to service multiple users through the output queue

5-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Which OUTQ?
IBM i

Program Job description


Job's temporary structures
Output to
printer
OUTQ (*USRPRF
name )
file User profile
Default

Printer file
output queue OUTQ ( *WRKSTN
name )
SPOOL(*YES) Device description

OUTQ
( *JOB
)
OUTQ (*DEV
name )
name
PRTDEV ( *SYSVAL
name )
System value

QPRTDEV (
PRT01
name )
© Copyright IBM Corporation 2002, 2014

Figure 5-5. Which OUTQ? AS068.1

Notes:
The default output queue for a job is determined at job start. If an OUTQ is specified explicitly at any
levels, then it is the OUTQ to be used.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Using a printer file


IBM i

EXTERNALLY DESCRIBED
PRTF pgm

Field level
Field level REPORT
descriptions
Descriptions copied
(and attributes)
(at compile time)
(attributes at open)

PROGRAM DESCRIBED
PRTF pgm

(Attributes) Field level descriptions in


output specifications REPORT
(attributes at open)

© Copyright IBM Corporation 2002, 2014

Figure 5-6. Using a printer file AS068.1

Notes:
A printer file describes how the system is to operate on data as it passes between your application
program and a printer. A printer file must be specified in your RPG IV program. On other systems,
you might code a physical printer device rather than a printer file. On the i, the printer file is the
interface between your RPG IV program and the physical printer devices.
In its simplest form, a printer file is a definition of basic formatting attributes that you want to use in
your report. In many cases, you simply use the i system-supplied printer files, QSYSPRT or QPRINT.
If you want to define your report formatting attributes specifically, you might create a printer device
file of your own or more likely, use a generic printer file created in your enterprise to handle a family
of similar printer devices.
The printer file is the file name for the F-spec that defines your printer output. In your program, the
actual definition of the report format can be accomplished in one of two ways:
1. Program-described printer files
Program-described printer files rely on the high-level language program to define records and
fields to be printed.

5-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty 2. Externally described printer files


Externally described printer files use data description specification (DDS) rather than the
high-level language to define records and field to be printed. You can specify the syntax and
attributes of the report together in an externally described printer file. In this case, field
description details are copied into the program from the printer file at program compile time. If
you use DDS, you specify the name of your DDS source file in the SRCFILE parameter of the
Create Printer File (CRTPRTF) command. DDS gives the application programmer better control
over how the printed output is formatted and printed.
Here is an example that shows you a few of the parameters included in a printer file for one of the
PRTF commands:
Change Printer File (CHGPRTF)

Type choices, press Enter.

File . . . . . . . . . . . . . . > APPDSC01S Name, generic*, *ALL


Library . . . . . . . . . . . > AS06V7LIB Name, *LIBL, *ALL, *ALL
Device:
Printer . . . . . . . . . . . *JOB Name, *SAME, *JOB, *SYS
Printer device type . . . . . . *SCS *SAME, *SCS, *IPDS, *LI
Page size:
Length--lines per page . . . . 66 .001-255.000, *SAME
Width--positions per line . . 132 .001-378.000, *SAME
Measurement method . . . . . . *ROWCOL *SAME, *ROWCOL, *UOM
Lines per inch . . . . . . . . . 6 *SAME, 6, 3, 4, 7.5, 7,
Characters per inch . . . . . . 10 *SAME, 10, 5, 12, 13.3,
Overflow line number . . . . . . 60 1-255, *SAME
Record format level check . . . *YES *SAME, *YES, *NO
Text 'description' . . . . . . . > 'Lost discount summary report'
:
:
:
:
Whenever your program outputs a printed report, a printer file is referenced that describes the
characteristics of the format of your output. Your F-spec must reference either an IBM - supplied
printer file (like QSYSPRT or QPRINT) or a printer file that you or someone else in your enterprise
has created. When using the IBM-supplied printer files, you must specify the syntax of the report in
output specs.
Following is a list of the IBM-supplied printer files:
QSYSPRT: A program-described printer file in library QSYS.
QPRINT: Default spooled output printer file for normal print.
QPRINTS: Default spooled output printer file for special forms.
QPRINT2: Default spooled output printer file for two copy output.
QPSPLPRT: Default spooled output printer file for the spooling subsystem.
Reference:
Basic Printing

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Printer file characteristics


IBM i

FILE ............................. File-level keywords


apply to all fields in
all Formats
---
| FORMAT ..................... Format-level keywords
| apply to all Fields in
| Format
| FIELD
| FIELD
| FIELD
---
---
| FORMAT
|
| FIELD .................. Field-level keywords
|
| - constant (for example, Headings)
| FIELD - variable (from program - for example, CustNo)
| - system (for example, System date)
---
---
| FORMAT
|
|
---

© Copyright IBM Corporation 2002, 2014

Figure 5-7. Printer file characteristics AS068.1

Notes:
• Smallest item to print is FIELD.
• Field types: Constant, variable, and system.
• Fields grouped together into a layout of FORMAT.
• Format can be a single line or entire page.
• Printer file can contain many formats (max 1024).
• Keywords specify additional print options:
- UNDERLINE
- HIGHLIGHT
- FONT change
• Keywords defined at field, format, and file levels.

5-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Printer file DDS


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-8. Printer file DDS AS068.1

Notes:
File-level keywords are entered before the record format name. The file level is terminated when
the record format name is processed.
Record-level keywords start on the same line as the record format name. The record level is
terminated by the first field or constant is named.
Field-level keywords start on the same line as the field with which they are associated and are
terminated when the next field or constant is specified.
Keywords and parameter values
• Code all DDS entries in uppercase except character literals enclosed in apostrophes.
• Code keywords on the same (or subsequent) line as the entry with which they are associated.
• Separate multiple keywords with at least one blank. Parameter values for keywords must be
enclosed in parentheses following the keyword.
• Use apostrophes to enclose character values. Numeric values appear without apostrophes.
• Use a minus (-) sign or a plus (+) sign as a continuation character when a keyword and its value
do not fit on a single line. The sign must be the last non-blank character in the functions field.
Reference: s
IBM i IBM Knowledge Center: DDS for Printer Files

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Printer DDS keywords


IBM i

ALIAS HIGHLIGHT UNDERLINE


CHRID LPI
CHRSIZ PAGNBR
CPI REF
DATE REFFLD
DFT SKIPA
DRAWER SKIPB
EDTCDE SPACEA
EDTWRD SPACEB
FONT TEXT

blank - Field level


- File level
- Field and record level
- File, field and record level
- Record level
© Copyright IBM Corporation 2002, 2014

Figure 5-9. Printer DDS keywords AS068.1

Notes:
Many of the DDS keywords are self-explanatory. We do not explain all of them in detail in class as
you need to use the IBM Knowledge Center DDS Reference until they become familiar to you.

5-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

PRTF DDS
IBM i

Record format name Reference DB file/field definition

Literal

Reference

Field name

This field is
defined in this
PRTF.

Space after
© Copyright IBM Corporation 2002, 2014

Figure 5-10. PRTF DDS AS068.1

Notes:
This visual introduces the format of DDS that you use to define a report format (print file). More
examples follow but for now, you should be aware that:
• Conditioning (Pos 7 - 16) indicators 01 - 99 may be used to determine record or field output.
Use AND / OR for more than three indicators.
• Type of Name (Pos 17) R indicates name of a record format, blank indicates a field name.
• Name (Pos 19 - 28) used to name a record format or a field.
• Reference (Pos 29) R indicates a copy of field attributes from a previous definition is requested
(works in conjunction with REF and REFFLD keywords), blank requires further field definition (that
is, length, data type and decimal positions, if needed).
• Length (Pos 30 - 34) designates length of a named field that is not referenced.
• Data type (Pos 35) specifies the data type associated with the field:
- S: Zoned decimal
- A: Character
- F: Floating point

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

• Decimal Positions (Pos 36 - 37) define decimal placement within zoned decimal field.
• Usage (Pos 38) defines field as output field, blank or O.
• Location (Pos 39 - 44) positions the beginning of a defined field.
- Line (Pos 39 - 41) specifies the line on the page in which a field begins. This can be used to
position a field on a specific line of the print-out. It cannot be used with the SPACE
keywords.
- Position (Pos 42 - 44) start of the field.
• Keywords (Pos 45 - 80) literal constants or keywords are specified.

5-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Output report: Example


IBM i

|...+....1....+....2....+....3....+....4....+....5....+....6....+....7..
5/02/00 Purchase Items Listing
Page: 1

Item No Description Qty On Hand Qty On Order Tot Avail

20001 Telephone, one line 10 6 16


20002 Telephone, two line 5 12 17
20003 Speaker Telephone 6 8 14
20004 Telephone Extension Cord 25 10 35
:
20026 Three Ring Binders 10 108 118
20027 Three hole punch 149 2 151
------------------------------------------------------------------------
5/02/00 Purchase Items Listing
Page: 2

Item No Description Qty On Hand Qty On Order Tot Avai

20028 Desk picture frame 5 X 7 47 120 16


:
20049 3 hole lined paper 10 4 14
20050 Heavy duty stapler 5 0 5
*** End of Listing ***

© Copyright IBM Corporation 2002, 2014

Figure 5-11. Output report: Example AS068.1

Notes:
This is a Purchase Items Listing sample report. It lists the item number, description, quantity on
hand, quantity on order, and total available for various item records from the item data file. If the
total quantity available is below 15, the total available field is underlined. Let us look at the DDS that
defines the printer file used for this example.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

PRTF: DDS example


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-12. PRTF: DDS example AS068.1

Notes:
Notice that there are separate record formats for the data that is heading-related, record (item
detail)-related and footing-related. We could add additional records as needed for subtotals and
totals.
For now, let us focus on several features of this example:
1. We reference the definition of fields already defined in the ITEM_PF file in the database. Also
notice the INDARA keyword. We use it with our PRTFS.
2. For the heading record, we specify skipping six lines before printing the line followed by one
blank line afterward.
3. A number of special keywords are available, such as DATE, TIME, and PAGNBR. These variables
are automatically defined in DDS and do not have to be referenced in your RPG IV program.
The system automatically supplies date and time values, and, in the case of page numbering,
automatically increments its value.
4. Keywords may be used to make a report more readable by specifying underline, for example.
5. Relative positioning of data is supported. In this case, the field will be started one space after
the previous field.

5-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty 6. Editing is supported in DDS in two ways:


• EDTCDE supports many edit codes that are explained in the DDS Reference Manual. Some of
the functions performed by edit codes are:
- Leading zeros are suppressed.
- The field can be punctuated with commas and periods to show decimal position and to
group digits by threes.
- Negative values can be displayed with a minus sign or CR to the right.
- Zero values can be displayed as zero or blanks.
- Asterisks can be displayed to the left of significant digits to provide asterisk protection.
- A currency symbol (corresponding to the system value QCURSYM) can be displayed
immediately to the left of the significant digit that is farthest to the left (called
floating-currency symbol). For fixed-currency symbols, use the EDTWRD keyword.
• EDTWRD allows you to create your own edit mask in DDS.
7. The field TOTQTYAVL is defined externally in the printer file and is available to your RPG IV
program without any further definition.
8. We have the UNDERLINE attribute controlled by an indicator, 43. Because we write RPG IV
programs with named indicators only, you must code the INDARA keyword at the file level. This
keyword enables us to map named indicators to numbered indicators.
Finally, the member type for a DDS described printer file is PRTF. When compiling the member, you
may execute the CRTPRTF command as follows on the next page:
Create Printer File (CRTPRTF)

Type choices, press Enter.

File . . . . . . . . . . . . . . > ITEMLIST Name


Library . . . . . . . . . . . > AS06V7LIB Name, *CURLIB
Source file . . . . . . . . . . > QDDSSRC Name, *NONE
Library . . . . . . . . . . . > AS06V7LIB Name, *LIBL, *CURLIB
Source member . . . . . . . . . > ITEMLIST Name, *FILE
Generation severity level . . . 20 0-30
Flagging severity level . . . . 0 0-30
Device:
Printer . . . . . . . . . . . *JOB Name, *JOB, *SYSVAL
Printer device type . . . . . . *SCS *SCS, *IPDS, *LINE...
Text 'description' . . . . . . . *SRCMBRTXT
:
:
:
Reference:
IBM i Knowledge Center – DDS for printer files, Keyword entries for printer files

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

PRTF RPG IV program: Itemlist


IBM i

1 3
4

2
3

© Copyright IBM Corporation 2002, 2014

Figure 5-13. PRTF RPG IV program: Itemlist AS068.1

Notes:
This program, together with the PRTF in the previous visual, produces the list of items that look
similar to the report that follows these notes.
Note the highlighted points in the program:
1. The printer file name matches the name of PRTF we coded using DDS and then created.
2. As we did with the earlier printer programs, we have a DoW loop that checks for End of File
using %Eof. %Eof is turned on (=1) when we reach EOF of the Item_PF data file.
3. The Overflow indicator is used to indicate overflow. It is tied to PRTF on the F-spec and is
turned on by the system when it senses overflow (page length and overflow line are set in
CRTPRTF). Overflow is tested in an IF statement.
4. Indicator 43 (numeric) was referenced in the DDS to be set to true if the Total Quantity Available
is less than 15. Note that *in43 is defined in the Printer File DDS. The quantity will be underlined
in this situation. Since we use only named indicators in RPG IV, we use the coding technique
shown to map each and every indicator defined in a PRTF. What we coded in the D-spec is
called a data structure. We spend more time explaining data structures in AS07/S6198. For
now, just use this technique when working with PRTFs that have indicators.

5-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty 5. *in43 is mapped to the named indicator, LowAvailQty. LowAvailQty and indicator 43 are now
the same.
6. Using an expression, we set LowAvailQty, which is indicator 43, to true or false based on the
result of the expression.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Edit codes for printed output


IBM i

Zero Balances FLT


Commas to Print No Sign CR __ __

Yes Yes 1 A J N Y=Date 5-9 =


User
Defined

Yes No 2 B K O

No Yes 3 C L P Z=Remove
sign from
numeric

No No 4 D M Q

© Copyright IBM Corporation 2002, 2014

Figure 5-14. Edit codes for printed output AS068.1

Notes:
There are a number of edit codes that you can use in your PRTF DDS. These codes handle many
of the most common situations that in other languages might require you to create your own edit
code or edit word.
User-defined edit codes are created by using the create edit description (CRTEDTD) command. Edit
codes 5 - 9 correspond to IBM-supplied edit code descriptions QEDIT5, QEDIT6, QEDIT7,
QEDIT8, and QEDIT9 in the QSYS library. Use the WRKEDTD *ALL command to see the detail of the
supplied descriptions. To replace an edit code, make sure that the IBM-supplied version is first
deleted by using the delete edit description (DLTEDTD) command.
The Y edit code inserts slashes (/) between the month day and year and suppresses the leftmost
zero of a date field.
The Z edit code removes the sign (+ or -) from a numeric field and suppresses leading zeros.
The X edit code originally converted signed values to unsigned values without suppressing the
leading zeros. The i now does this automatically.

5-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Checkpoint
IBM i

1. True or false: Exact line numbers can be used to position a


particular field or constant on the report.

2. Which of the following DDS facilities are available when


defining printer files?
a. Continuation lines
b. Edit codes and edit words
c. Field definition referencing
d. All of the above

3. What are the three levels at which DDS printer file keywords
can be specified?

© Copyright IBM Corporation 2002, 2014

Figure 5-15. Checkpoint AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Display file descriptions


IBM i

• They define one or more panels (record formats).


• One display file contains all panels for one program or an
entire application.
• They are coded using DDS (such as printer and database
files).
• They can be created or tested using:
– RDI Screen Designer
• They are defined at three levels:
– File
– Record
– Field

© Copyright IBM Corporation 2002, 2014

Figure 5-16. Display file descriptions AS068.1

Notes:
Display files are defined using DDS. Keywords enhance your file definitions and can be applied at
the file level, the record level, and the field level.
Display files can have one record format or several record formats.
Keywords apply at the file, record, and field levels. Some keywords can be used at just one level
while others can apply at more than one level.

5-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Display record format


IBM i

• It is the basic unit of information that is passed between a user


and a program.
• It is sent by one Write or ExFmt operation.
• It occupies all lines of a display starting with the lowest defined
line number and including all lines that are used and unused
through the highest defined line number:
– Smallest format occupies one line on the display.
– Largest display format occupies all lines of the display.
• Multiple display formats can be displayed at the display device.
• The limit per display file is 1024 record formats.

© Copyright IBM Corporation 2002, 2014

Figure 5-17. Display record format AS068.1

Notes:
Display formats behave by default in the following manner:
• They write a display format:
- Clears the device of all previous formats
- Unlocks the keyboard for input
• They read a display format:
- Locks the keyboard from input
• All input and input/output (I/O - both) fields are underlined.
• All character data entry is uppercase.
• DDS validity checking (if specified by the programmer) causes:
- Field in error to be displayed in reverse image
- Cursor to move to beginning of field in error
- A message to appear
- Keyboard to lock

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Display design (1 of 5)
IBM i

ITEMINQ Item Inquiry 6/21/00

Item Number . . . . . .: 10005

Press Enter to continue


F3=Exit

Item not found on file - please correct

© Copyright IBM Corporation 2002, 2014

Figure 5-18. Display design (1 of 5) AS068.1

Notes:
Let us assume that we have been asked to develop an application that prompts a user for an item
number. Randomly read the item master file and display.
1. The detailed information about the item entered as shown in the following visual when the item
number exists in the file.
2. The prompt display (shown above) with an error message conditioned by the result of the chain
if it was unsuccessful.

5-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Display design (2 of 5)
IBM i

ITEMINQ Item Inquiry 6/21/00

Item Number . . . . . .: 20005


Description . . . . . .: Dry Erase Marker Packs

Quantity on hand . . .: 428


Quantity on order . . .: 10

Supplier Number . . . .: 10010


Supplier Catalog No . .: V145125

F3=Exit F12=Cancel

© Copyright IBM Corporation 2002, 2014

Figure 5-19. Display design (2 of 5) AS068.1

Notes:
This is the detailed information that is displayed for a valid item, in this case, item number 20005,
rather than 10005 which was invalid.
We corrected the item number on the previous screen 10005 - 20005 (which we did not show you).

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Display design (3 of 5)
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-20. Display design (3 of 5) AS068.1

Notes:
DDS is used to describe a display file. The DDS can be written manually by entering directly into a
source member, or can be generated using Screen Designer in RDi as a design and DDS
generation tool.
We must produce the DDS source, type DSPF, to create the display file. The display file, as
explained previously, contains two record formats of which this is the first format. When using RDi,
this is what the layout of the format looks like.
This prompting format is used for inquiry of the item master file by using item number.
An error message is displayed if the item number entered is an invalid one.

5-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Display design (4 of 5)
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-21. Display design (4 of 5) AS068.1

Notes:
This is the second display format. It displays the information for the item when it is found
successfully. Also, note the message warning of a low stock situation.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Display design (5 of 5)
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-22. Display design (5 of 5) AS068.1

Notes:
This DSPF illustrates the following elements:
1. F-keys at file/format level
2. Field-level keywords (EDTCDE)
3. DSPATR and COLOR keywords at field level
4. Elementary error message handling (ERRMSG)
5. Conditioning Indicator for field existence and presentation
For display files in general:
• Conditioning (Pos 7 - 16) option indicators 01 - 99 are used to condition record or field output;
use AND OR for more than 3 indicator conditioning.
• Type of Name (Pos 17) R indicates name of a record format, blank indicates a field name.
• Name (Pos 19 - 28) used to name a record format or a field.
• Reference (Pos 29) R indicates reference to a previously defined file for field attributes.

5-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • Length (Pos 30 - 34) used to determine length of field, if not referenced. This length does not
include beginning or ending attribute characters of the field, even though field positioning on the
screen must consider the attribute characters. This length is also known as the program length
of the field.
• Data type/KB shift (Pos 35) designates type of data or keyboard shift attributes for a field.
• Usage (Pos 38) specifies a field to be (O)utput, (I)nput, (B)oth I and O (H)idden, a special
output/input field, and (M)essage, a special output field.
• Location (Pos 39 - 44) determines the exact location on the display where each field begins.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Display attribute (DSPATR)


IBM i

DDS Keyword Meaning

• DSPATR (UL) Underline


• DSPATR (BL) Flashing field
• DSPATR (CS) Column separator
• DSPATR (HI) High intensity
• DSPATR (ND) Non-display
• DSPATR (RI) Reverse image
• DSPATR (MDT) Set on modified data tag
• DSPATR (PC) Position cursor
• DSPATR (PR) Protect field

© Copyright IBM Corporation 2002, 2014

Figure 5-23. Display attribute (DSPATR) AS068.1

Notes:
The DSPATR keyword requests one or more attributes for the same field. You can specify one
keyword with multiple attributes or you can specify multiple keywords, each with an attribute. For
example, DSPATR(CS RI) is the same as specifying DSPATR(CS) followed by DSPATR(RI). Another
example is that DSPATR(UL HI RI) is the same as DSPATR(ND).

5-32 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

DSPATR and color displays


IBM i

DSPATR(CS) DSPATR(HI)
DSPATR(BL) display Color produced on the
display attribute display attribute
attribute selected color display station
selected selected

Green (normal)

X Turquoise

X White

X Red, no flashing

X X Red, with flashing

X X Yellow

X X Pink

X X X Blue

© Copyright IBM Corporation 2002, 2014

Figure 5-24. DSPATR and color displays AS068.1

Notes:
When you specify the DSPATR keyword (without the COLOR keyword), fields are displayed on color
displays with the colors in visual table but without the display attributes that you specified.
For example, if you specify DSPATR(BL HI), a color display shows the field in red with flashing.
Be aware of this when you are coding on a color display device.
Reference:
IBM i Knowledge Center - DDS: DDS for display files, DDS Keyword entries for display files

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Enabling function keys


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-25. Enabling function keys AS068.1

Notes:
Display file source code can have DDS keywords coded at the file, record, and field levels. This
example illustrates various display file keywords coded at each of the three levels.
Note that function keys are enabled at both the file level and the record-level.
CA12, coded at the record-level (2), specifies that when DETAIL is in use, F12 is enabled. CA03 is
also enabled for this display record format because it was coded at the file level (1).
Using a response indicator with the function key is optional. However, the indicator is very useful in
your program. It is the convention that the indicator number matches the function key number, but,
this is not mandatory.

5-34 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Function keys
IBM i

NAME_____
HOURS_____
CF06(30) CA08(15)

Data USER No data


transmitted PROGRAM Transmitted
15

30

Data sent to program:


IND NAME HOURS
CF:
CA: NO FIELDS
© Copyright IBM Corporation 2002, 2014

Figure 5-26. Function keys AS068.1

Notes:
• Input record content - Workstation to i (program).
a. Workstation ID (WSID)
b. Function key that ended transaction
c. Cursor position
d. Address and data for each input-capable field with modified data tag (MDT) ON
• The above information is formatted by workstation data management.
• A READ makes the information available to the program.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Field-level keywords
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-27. Field-level keywords AS068.1

Notes:
This example illustrates various display file keywords coded at the field level.
Note that keywords, such as DATE, TIME, and SYSNAME, are keywords that retrieve and display the
obvious system values.
You can use the USER field-level keyword to display the user profile name for the current job as a
constant (output-only) field that is 10 characters long. Use the SYSNAME, USER, DATE, and TIME
field-level keywords to display the appropriate information as a constant on your display formats.
We also use the ERRMSG keyword to be displayed when data entered into this field on the screen is
in error. If it is, the user sees an error message and has to correct the data.

5-36 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Validity checking keywords


IBM i
CHECK(XX)
ME: Mandatory Enter LC: Lowercase
MF: Mandatory fill RB: Right justify/Blank fill
FE: Field exit check RZ: Right justify/Zero fill
COMP (Relational-Operator value) EQ, NE, LT, NL, GT, NG, LE, GE
CMP (Relational-Operator value)
Example: FIELD 1 --------------- COMP(EQ 'ABC')
FIELD2 --------------- COMP(NG 1000)
RANGE (Low-Value High-Value)
Example: FIELD1 ---------------- RANGE('A' 'F')
FIELD2 --------------- RANGE(1 1000)
VALUES (Value1 Value2 ------ Value 100)
Example: FIELD1 ---------------- VALUES('A' 'B' 'C')
FIELD2 ---------------- VALUES(33 42 01)
CHKMSGID: Allows a user-defined message when validity check error is detected
Example: FIELD1 ---------------- RANGE (1 50)
---------------- CHKMSGID(MSG1044 MSGFILE)

© Copyright IBM Corporation 2002, 2014

Figure 5-28. Validity checking keywords AS068.1

Notes:
It is very easy to edit data entry, control certain keyboard functions and move the cursor as your
users key data. DDS keywords are available for many of these functions.
Validity checking keywords help offload data entry edit tasks from your program. i5/OS (OS/400)
takes on the task of performing some of the more basic edits of your users' input.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

DDS message keywords


IBM i
• ERRSFL
– Provides system-supplied subfile
– Displays multiple messages at once
– Allows message scrolling
• ERRMSG
– Specifies message text
– Associates messages with a data field
– Detects program errors
– Appears at bottom of display
• ERRMSGID
– Uses text of predefined message
– Associates messages with a data field
– Detects program errors
– Appears at bottom of display
• CHKMSGID
– Uses text of predefined message
– Associates message with data field when used with the CHECK keyword
– Detects DDS errors on the display
– Appears at bottom of display

© Copyright IBM Corporation 2002, 2014

Figure 5-29. DDS message keywords AS068.1

Notes:
There are many options for message handling on your displays. Some things to consider before
you choose a method:
• Are you using predefined or impromptu messages?
• Where on the display would you like the message?
• Is the message the result of a program edit?
• Does DDS perform a validity check?
• Is the message really a constant?
Note that ERRMSG and ERRMSGID require the use of indicators and are associated directly with data
fields. Any display that uses these messages must be coded in similar fashion. What happens
when your message or indicators must change?
Additional options: The DDS keyword MSGLOC (message location) designates the line of the
display on which error messages are displayed. For example, MSGLOC(22) sets line 22 as the line
for error messages. If the keyword is not used, the message line position defaults to line 24 (on a
standard 24 x 80 screen).

5-38 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty Use the ERRSFL keyword if multiple messages may potentially be displayed when a record format is
written to the display. The system displays an error subfile on the message line. This allows the
user to page through all of the error and validity messages issued.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-39
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Message coding examples


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-30. Message coding examples AS068.1

Notes:
&MSGTXT contains replacement text for the specified message. It must have a corresponding
character field designated for usage P (column 40 - program to system field) in the record format in
which it is to be used. This allows you to load the data field at program execution with variable data
that is substituted into the body of your predefined message. Of course, your predefined message
has substitution parameters defined to accept the data from this field.
An example of the ADDMSGD command that can be customized at program execution time follows:
ADDMSGD MSGID(MSG0021)
MSGF(OL86999/MSGF1)
MSG('Item &1 is no longer available.
It has been replaced with &2.' )

5-40 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Creating and using screen formats


IBM i

User steps
Create DDS
using Screen Data path
Designer/LPEX
Editor Syntax
checking
DDS
source
Listing file
of source
descriptions member X
and errors Create
display file
member Y
(Compile DDS source)

Display file member Z


Format 1
Format 2 Compiled Program
Format 3 Execution
Execute Format 2
Format 4 Execute Format 5
Format 5
© Copyright IBM Corporation 2002, 2014

Figure 5-31. Creating and using screen formats AS068.1

Notes:
These steps should look familiar. Display file members are DSPF type members. After creating the
display file (object) with multiple formats, a program can be written and compiled to use them.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-41
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

RPG screen operations


IBM i

Format PGM A

Write
..
.
ExFmt
Read Format

© Copyright IBM Corporation 2002, 2014

Figure 5-32. RPG screen operations AS068.1

Notes:
The RPG IV WRITE operation sends formatted data from the program to the display device buffer.
The EXFMT operation performs a write, displays the data, and then performs a read when a
function key or Enter is pressed.
The READ operation retrieves information from the display device buffer into the RPG IV program.

5-42 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Inquiry example: Item inquiry program


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-33. Inquiry example: Item inquiry program AS068.1

Notes:
1. Both Item_PF and ItemInq are externally described. The input and output specs for the
display file will be copied into the program at RPG IV compile time. Note that the name used in
the F-spec corresponds with the name of the display file. The file is designated a (C)ombined
WORKSTN type of file for use with display station input and output.
2. A common technique used to code interactive processing is to code the display of a screen in a
loop using in this case, the DoW operation code conditioned by the F3 (exit) key.
3. ExFmt is the RPG operation that writes then reads a display format. The ExFmt opcode writes
the record format to the screen, waits for input from the user, and then reads the data from the
display and passes it to RPG IV.
4. If the CHAIN is successful, data from the DETAIL record format is displayed with the ExFmt
operation.
5. The only situation that should be controlled is when no record is found during the CHAIN (invalid
key - record not found). We have coded an error message in the display file that is conditioned
on *In40. Note that in the program, *In40 (NotFound) is set on when there is no record found
as a result of the CHAIN. If the CHAIN is unsuccessful, our error message is displayed when the

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-43
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

display format is written. The user sees the error message, presses error reset to unlock the
keyboard, and tries another customer number by pressing F12 or presses F3 to end the inquiry
program.
6. Also, notice the structure that we discussed in the printing unit again. Because DDS supports
only numbered indicators, we must map the numbered indicators in DDS to our named
indicators. To do this, we specify the INDARA keyword in the display file and the IndDS keyword
in the RPG IV program.

Note

Because the field names from the database file and the field names from the display file match,
there is no need to code EVALs to assign values from the data file to the display file.

The DDS for the Item_PF follows:


A*****************************************************************
A* Item Master PF: ITEM_PF
A*****************************************************************
A REF(DICTIONARY)
A UNIQUE
A R ITEM_FMT TEXT('Item Master Record')
A ITMNBR R
A ITMDESCR R
A ITMQTYOH R
A ITMQTYOO R
A ITMCOST R
A ITMPRICE R
A VNDNBR R
A ITMVNDCAT#R
A K ITMNBR
A K CUSTNO

5-44 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Machine exercise: Coding an inquiry program


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 5-34. Machine exercise: Coding an inquiry program AS068.1

Notes:
Perform the Coding an inquiry program machine exercise.

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-45
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Checkpoint
IBM i

1. True or false: For interactive inquiry, display record formats


must use the same field names as the database file being
processed.

2. Which of the following are used to validate data entry fields?


a. CHECK
b. DSPATR
c. RANGE
d. All of the above

3. True or false: An inquiry program requires at least two display


record formats.

© Copyright IBM Corporation 2002, 2014

Figure 5-35. Checkpoint AS068.1

Notes:

5-46 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Unit summary
IBM i

Having completed this unit, you should be able to:


• Use DDS to define the layout of a report
• Create a printer file (PRTF)
• Write an RPG IV program that prints a report using a printer
file defined in DDS
• Describe the properties of a display file
• Create display files using DDS
• Use Exfmt and write RPG IV operation codes with display files
• Write inquiry RPG IV programs to support one display file

© Copyright IBM Corporation 2002, 2014

Figure 5-36. Unit summary AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 5. Using printer and display files in an RPG IV program 5-47
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

5-48 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 6. Structured programming, error handling,
subprocedures, and subroutines

What this unit is about


This unit describes how to write structured RPG code. It discusses how to
build and control loops, how to condition execution of RPG IV code, and how
to write and use subroutines within an RPG IV program.
This unit further describes the use of If, Select/When/Other, and Iter/Leave in
loops. You also learn how to execute subroutines using ExSr.

What you should be able to do


After completing this unit, you should be able to:
• Write structured RPG IV code
• Write RPG IV code with conditional If, DoW, DoU, and For opcodes
• Write RPG IV code with conditional Select groups
• Determine the number of nesting levels for a nested group
• Describe how to use the %Error and %Status BiFs with the error (E)
extender
• Write code for a subprocedure in an RPG IV program
• Describe the usage of subroutines in older RPG IV programs

How you will check your progress


• Checkpoint questions
• Machine exercise
- In this exercise, the students are given a program that they modify to
produce a more structured program by coding subroutines.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:


• Write structured RPG IV code
• Write RPG IV code with conditional If, DoW, DoU, and For
opcodes
• Write RPG IV code with conditional Select groups
• Determine the number of nesting levels for a nested group
• Describe how to use the %Error and %Status BiFs with the
error (E) extender
• Write code for a subprocedure in an RPG IV program
• Describe the usage of subroutines in older RPG IV programs

© Copyright IBM Corporation 2002, 2014

Figure 6-1. Unit objectives AS068.1

Notes:

6-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Introducing structured programming


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-2. Introducing structured programming AS068.1

Notes:
This visual shows some of the functions available in RPG IV to assist the programmer to write
structured programs. Some of the techniques that you can code include:
• If/Else/ElseIf/EndIf
• Looping DoW/DoU/For
• Select groups
• Subroutines
External calls to other programs or procedures are covered later in this unit.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

If operation code
IBM i

Chain to vendor record

F
Record
found?
T

F
Active
record?

Calculate order value

© Copyright IBM Corporation 2002, 2014

Figure 6-3. If operation code AS068.1

Notes:
The If operation code is one of the opcodes that are used to condition the flow of your calculations.
Note the form of the If opcode in this example. The result of the expression is either true or false. If
the condition is true, the code that follows the If is executed. Otherwise, the program skips directly
to the EndIf statement.
Each IF group must be terminated with an EndIf statement. Since If groups can be nested, the
EndIf not only ensures that you correctly terminate an If, it also makes your code easier to read and
maintain.
In this example, the code wants to process only active records. Therefore, the If is conditioned such
that it tests for an active record and that the end of the file has not been reached.
You can see a new opcode (Chain) and a new BiF (%Found) in this visual.
Chain performs a random read of a record using a search argument (in this case VndNbr). This
search argument is matched to the record key.
The %Found BiF is coded and set to true or false (1 or 0) depending on whether a record was
found in the previous input operation (Chain, in this example). Although the filename parameter is
optional, it is recommended that you always code it to make your code clear and easier to
maintain.

6-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

If and Else
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-4. If and Else AS068.1

Notes:
This visual is designed to show you the structure of If statement groups:
• The rules for the comparison using an If are the same as you would expect for any logical
comparison. The fields must be the same type.
• Each If must be terminated by an EndIf.
• The Else operation is an optional part of an If group. If the If comparison is met, the calculations
before Else are processed. Otherwise, the calculations after the Else are processed.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Make your expressions clear


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-5. Make your expressions clear AS068.1

Notes:
Which is more easily understood? It is recommended that you always code expressions that
explain the condition clearly. Also, you can see that rather than writing If Indicator = *on, it is better
to code If Indicator. It is true for testing of *off, as well.

6-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

'AND' or 'OR' in expressions


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-6. 'AND' or 'OR' in expressions AS068.1

Notes:
This example shows you an example of using an 'AND' or 'OR' in an expression.
Note the use of parentheses to clarify how each component of the expression is evaluated. In
addition, free format coding enables you to indent your code so that it is more easily read.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Nested structured groups


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-7. Nested structured groups AS068.1

Notes:
If a structured group of various opcodes that can condition calculations contains another complete
structured group, together they form a nested structured group. Structured groups can be nested
to a maximum depth of 100 levels.
The visual is an example of nested structured groups, three levels deep.

6-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Nested If/Else
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-8. Nested If/Else AS068.1

Notes:
The 1, 2, and 3 in the visual mark the beginning and end of each group within this nested group.
Notice a new opcode, Update. This opcode replaces a record in a file with changed data. There is
more about Update in another unit.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Select/When/Other
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-9. Select/When/Other AS068.1

Notes:
The select group conditionally processes one of several alternative sequences of operations. It
consists of:
• A Select statement
• One or more When groups
• An optional Other group
• Endsl statement
Code can be grouped within a Select/Endsl pair. When can be used to condition execution of a
Select group.
The system compares the value of RegPay for each When statement. If a comparison is satisfied in
one of the When statements, the code that follows that When is executed. Execution of the When
group is terminated by the next When, Other, or Endsl that is encountered. Any When or Other
group that follows the When satisfying the comparison test is bypassed. If both Whens in the
example do not satisfy the comparison, the code that follows the Other is executed.

6-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

If versus Select group


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-10. If versus Select group AS068.1

Notes:
This example shows a combination of the use of If and a Select/When/Other group.
Look at the three examples. The coded function is identical. Which is easiest to understand and
hence maintain? Also, notice the coding of the ElseIf statement within an If rather than a nested If
statement under an Else.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Do While (DoW) and Do Until (DoU)


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-11. Do While (DOW) and Do Until (DOU) AS068.1

Notes:
Do While (DoW) and Do Until (DoU) are opcodes that allow you to code a loop. Iterations can be
managed in the loop with a counter or a condition in an expression and can be tested to determine
whether looping can continue or be terminated. Several operations can change the normal flow of
the loop (ITER and LEAVE). A loop always begins with DoW or DoU and is ended by an EndDo.
The DoW operation code precedes a group of operations you want to process while a certain
condition exists. A logical condition is expressed by an indicator valued expression (result is '1' or
'0'). The operations that are controlled by the DoW operation are performed while the expression is
true.
The condition is tested before the code within the loop is executed.
The DoU operation code precedes a group of operations you want to execute at least once and
possibly more than once. The operations controlled by the DoU loop are performed until month =
12 is true.
The condition is tested after the DoU group is performed.
Use blank lines and comments to separate Do groups to make your code more readable.
Within a DoW or DoU group, there are several other statements that you can use.

6-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty The Leave operation is used within a Do loop to cause a premature exit of the loop before all
operations are completed.
The Iter operation transfers control from within a do group to the EndDo statement of the do group.
It can be used in DO loops to transfer control immediately to the EndDo statement. Iter causes the
next iteration of the loop to be executed.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

For/EndFor
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-12. For/EndFor AS068.1

Notes:
For and EndFor is another form of looping. The For/EndFor loop offers you flexibility in how you
control the loop.
You can increment or decrement a variable by an integer amount.
The visual illustrates how the For/EndFor operates under different circumstances:
• If no Starting value is specified, the Index retains its original value.
• If no Increment is specified, it defaults to 1.
• If no Limit value is specified, an indefinite loop results. (Some other condition within the loop is
used to terminate.)

6-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Program problems
IBM i

2+2=5

File Problem

Logic

Exception
(circumvent) Error
• Trap it
(graceful abend)
• Identify cause and provide information to user
• Take appropriate action
© Copyright IBM Corporation 2002, 2014

Figure 6-13. Program problems AS068.1

Notes:
Coding exception-handling logic in your programs reduces the number of abnormal ends; namely,
those associated with function checks.
Error handling can be included to your RPG IV code in anticipation of possible problems or they can
be added as workarounds after an application has been placed into production. In general, errors
and exceptions can be classified as:
1. File errors, such as file not found, file or record locked and so on.
2. Program errors, such as division by zero and decimal data errors.
3. Logic errors (errors that we code ourselves). Often these errors are discovered and corrected
during testing and debugging. However, sometimes they manage to remain and haunt us during
production.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Exceptions and methods


IBM i

• Some possible exceptions:


– Duplicate key
– Data decimal error
– Divide by zero
– Called program not found
• Processing halts and message issued:
– *ESCAPE: severe
– *STATUS: provides program status
– *NOTIFY: seeks reply from user
– Function check: unhandled exception
• Some possible actions:
– Save totals
– Identify the record last processed
– Notify operator
– Close all open files or data areas
– Implicit exit to error-handling subroutine

© Copyright IBM Corporation 2002, 2014

Figure 6-14. Exceptions and methods AS068.1

Notes:
What do you want to happen when:
• Your program experiences a duplicate key error?
• You encounter a Decimal Data error?
• You experience an error caused by a division by zero?
• A called program is not found?
Runtime errors cause the system to suspend your program and issue a message to the interactive
user (or the system operator if the program is run in batch) of your program.
If you do not address potential data or logic problems in your code, you encounter errors and
processing halts.
Exception handling is the process that involves one or more of these steps:
• Examine an exception that has been generated as a result of a runtime error
• Modify the exception by handling it

6-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • Recover from the exception by passing the exception information to specific code in the
program that caused the problem or perhaps, to another program to take any necessary
actions.
When a runtime error occurs, an exception message is generated. An exception message has one
of the following types depending on the error that occurred:
• *ESCAPE: Indicates that a severe error was detected.
• *STATUS: Describes the status of work being done by a program.
• *NOTIFY: Describes a condition requiring corrective action or reply from the calling program.
• Function Check: Indicates that one of the three previous exceptions occurred and was not
handled.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Methods of managing exceptions


IBM i

• Handled by programmer:
1. The E opcode extender and the %Error BiF
2. Monitor group
3. ILE condition handler
4. Implicit exit to error subroutine

• Handled by IBM i:
5. Default error handler
Anticipate errors
Handle errors in your code
Minimize user panic

© Copyright IBM Corporation 2002, 2014

Figure 6-15. Methods of managing exceptions AS068.1

Notes:
Unless you write specific error handling code in your RPG IV programs, IBM i invokes the Default
Error Handler to handle any program exceptions. The Default Error Handler can manage the
entire exception process. However, the user is presented with an error message that he does not
know how to handle and your program more than likely has to be canceled.
When the Default Error Handler assumes responsibility for handling an error, either you wrote no
error handling code in your RPG IV program or you exhausted the possibilities that are handled by
your code.
Using the E-extender and %Error is a technique that gives you control of the action taken and the
messages that are displayed when a program or file exception is encountered.
However, you can avoid passing control in an exception situation in many cases by coding some
basic logic in your programs. A list of potential actions follows:
1. Use the E opcode extender and the %Error BiF. This technique requires that the opcode
supports this method.
2. Code a monitor group.

6-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty 3. Code an ILE Condition Handler - this can be a more complex method and should be used in
those situations where the first two methods do not address the exception in an adequate
manner.
4. Exit to an Error Subroutine, INFSR or *PSSR. This method is not recommended.
The recommended methods are the first two in the list.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

IBM i logic flow for error handling


IBM i

Exception/ No Execute next


error sequential instruction
Yes C

Set up file information or


program status data Cancel No
structure with
dump?

Yes
Yes
E-Extender? One method
or the other Issue dump

No

Indicator in Close files and indicate


73 and 74 of Yes program termination with
operation error
code

No
Yes Free program so it can be
Monitor Group?
called again
No
ILE Condition Yes
Handler? Set return code and issue
escape
No
message CEE9901
INFSR or
No
*PSSR Issue message to
subroutine requester
Return to caller
present

Yes Response No Continue


Cancel? program

Yes
C

© Copyright IBM Corporation 2002, 2014

Figure 6-16. IBM i logic flow for error handling AS068.1

Notes:
This flowchart illustrates the sequence of events followed by the Default Error Handler. Notice that if
no other method is selected, a system-supplied message is sent to the operator who is given the
option to cancel the program. If cancel is selected, files and data areas of the active program are
closed and control is returned to the calling program. If there was a calling program, it too, would
experience a system-supplied message and would halt, giving the user an opportunity to cancel it
as well.
Your users see a cryptic system message that does not provide a recommended course of action. It
would be better for your application to take control when an exception occurs and override any
default error message with a more informative and easily understood message.
The Yes branches from the decision blocks mean that your program told IBM i that your code
handles this specific error.
Notice that the flowchart shows the priority of the exception handlers:
1. The E-extender handler and %Error (or an error indicator; obsolete).
2. MONITOR group.
3. ILE condition handler.

6-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty 4. I/O error subroutine handler (for file errors) and Program error subroutine handler (for all other
errors); both methods are obsolete.
5. Default handler for unhandled exceptions.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Using the (E) extender


IBM i

• (E)rror opcode extender:


– Used with a limited range of operations
– Most file-handling operations: Read, Chain, Setll, and so forth
– Also used with Callp, In, Dsply, Test, and so forth

• %Error:
– Returns *On or *Off
– Value is set to *Off before the operation begins
– Normally used with %Status to determine the exact cause

• %Status:
– Returns 0 if no error has occurred since the beginning of the last
operation that specified the (E) extender
– %Status(file) returns the same value as the *Status field in INFDS
– %Status returns most recent value set for program or file status
© Copyright IBM Corporation 2002, 2014

Figure 6-17. Using the (E) extender AS068.1

Notes:
The visual summarizes how %Error and %Status work in conjunction with the E-extender for
opcodes.
There are other means of handling errors that we do not discuss in this class, but, RPG IV provides
five ways to code HLL-specific handlers and to recover from an exception:
1. (E) operation code extender: recommended
2. Monitor group: discussed in AS10/AS100
3. ILE Condition Handler: discussed in AS10/AS100
4. INFSR error subroutine: not recommended
5. *PSSR error subroutine: not recommended
The highlighted methods are the ones that we recommend with your code. You might experience
the other methods when maintaining legacy applications. Modify the code to use the newer
techniques wherever possible.
When you are using the (E) extender, the relevant program and file error information can be
obtained by using the %Status and %Error built-in functions.

6-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

E-extender, %Error, and %Status


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-18. E-extender, %Error, and %Status AS068.1

Notes:
In this example, we are using several BIFs to determine what is the problem when we encounter an
error. Notice that:
• %Error is set to ‘1' if an error occurs.
• To determine the specific error, we use the %Status BiF. %Status is used to fetch file and
program status codes that tell you whether something went wrong and what the error
was. %Status is set by file and program status code errors.
• In this case, we test for end of file using the %Eof BiF. Always use the specific file name that
you are testing with %Eof. The %Eof is set as a result of the latest read or write. If you do not
specify the file name, you may get a result for another file that you did not expect.
To enable the (E) operation code extender handler, you code an (E) or (e) with any of the operation
codes that support the e-extender. They are listed in the ILE RPG IV Reference Manual.
Coding the (E) extender affects the value returned by the built-in functions %Error and %Status for
exceptions. You can then use these built-in functions to test the returned values and determine
what action to take.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

If an 'E' operation code extender is present on the calculation specification and the exception is one
that is expected for that operation:
• The return values for the built-in functions %Status and %Error are set. Note that %Status is
set when any exception occurs even if the 'E' extender is not specified.
• The exception is handled.
• The program resumes.

6-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Program status data structure


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-19. Program status data structure AS068.1

Notes:
The IBM i provides information about the program. This information can be retrieved using a special
data structure, the Program Status Data Structure. This data structure does not relate to any
particular file. Instead, it provides information about the processing being done by the program.
A program status data structure has predefined subfields that are accessible by keyword or by
position.
The locations of certain frequently used information fields are associated with reserved system
names that can be specified in place of their positions:
• *ROUTINE retrieves the name of the called RPG routine in which the error occurred.
• *STATUS has the same meaning as it does for files, although as we see, the values of the
status codes that are returned are different.
• *PARMS is a 3-digit whole number that contains a count of the number of parameters that are
passed to this program by the calling program.
• *PROC is a character field 10-positions long, containing the name of the procedure (often the
program name) in which this program status data structure is specified.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

This example uses the E extender and the %Error BiF with the Call operation.
While we show you how to code the *Status field in the program status data structure, we do not
reference it in the calculations. We actually do not need to have coded it at all as %Status fetches
the value for us. The %Status BiF is set whether or not you have coded the PSDS in your program.
If the program attempts to run the Call opcode and an error occurs, %Error returns a value of ‘1’. If
the value of %Status equals 211, the program, PGMA, was not found and a subroutine named
ErrorSR is executed.
But, even though we gracefully identified the error and executed a subroutine:
• What else should we be doing after the subroutine has completed execution?
• Where should the program continue processing?
The subroutine to handle the error could be any name that you want.
References:
ILE RPG for Reference Manual, RPG IV Concepts File, and Program Exception/Errors

6-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Examples of program status codes


IBM i

*Status Explanation

00121 Invalid array index


00202 Called program failed
00211 Called program not found
00231 Called program halt indicator on
00333 Error on display operation
00414 Not authorized to use data area
00415 Not authorized to update data area
00431 Data area previously locked
00907 Decimal data error
00999 System program exception error

© Copyright IBM Corporation 2002, 2014

Figure 6-20. Examples of program status codes AS068.1

Notes:
Any program status code of 0100 or greater is considered to be an exception. If you coded the
E-extender with %Error, %Error would be set to ‘1' for any of the above codes that apply.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

What else is in the program status data structure


IBM i

From/To Field contents

16 - 20 Previous status code


21 - 28 RPG IV source sequence number
40 - 46 Exception error ID (MCH or CPF)
201 - 208 Name of file last used
244 - 253 Job name
254 - 263 User name
264 - 269 Job number
276 - 281 System date in UDATE format
288 - 293 Date compiled
304 - 333 Source file/library/member

© Copyright IBM Corporation 2002, 2014

Figure 6-21. What else is in the program status data structure AS068.1

Notes:
Much more information is available in the program status structure than what can be retrieved using
the reserved system words. Notice that both exception error IDs and the complete job name,
including the user name, are available to the program. Some of the other information that is shown
here can be very useful when changing or debugging a program.
To retrieve this additional information, the POS keyword must be coded on the Data specifications
for the data structure. If wanted, these entries can be mixed with ones that use the reserved system
words.

6-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Error handling recommendations


IBM i

• You can never add too much error handling code.


• The process is iterative.
• Tools and techniques recommendations:
– Use E-extender and %Error
– Use %Status
– Use PSDS and INFDS for specific information
– Code error handling and recovery in subprocedures
– Code %Error and %Status immediately after operation and before
other I/O BIFs
• Available BiFs focus heavily on I/O opcodes.
• Use monitor groups. (not discussed in this class)
• But, always check for errors before they happen:
– Zero divisor
– Numeric overflow
– Decimal data error
– Array index zero, negative, or greater than number of elements
© Copyright IBM Corporation 2002, 2014

Figure 6-22. Error handling recommendations AS068.1

Notes:
We have now talked about a number of ways your code can handle errors to avoid having the
default error handler that you are taking care of the problem.
However, many of these techniques (mostly BiFs) apply mainly to the I/O opcodes and a few others
(Call and In, for example). There are no similar BiFs for Eval, For, DoW, DoU, and other free form
opcodes that support free form expressions.
The best plan for handling errors is to anticipate them and avoid them in your programs.
Check for a zero divisor. Make sure that your result fields are large enough to hold the result of the
expression.
When coding error handling BiFS (%Error and %Status), be sure that your error handling logic is
processed before any other I/O BiFs.
If %Error is true, the value of the %Found, %Equal, and %Eof BiFs should be ignored.
Finally, error handling is a never-ending process. There is always more to learn and more error
handling code to add.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Calls in RPG IV
IBM i

• Why call other programs?


– Execute logic not included in your program
– Write once, use many times
• How?
– Dynamic Call:
• Call opcode: Legacy method
• Callp opcode: Uses prototyping to reduce errors
– Static Call:
• 'Bound Call'
• Less overhead at runtime
• Use Callp or Callb opcode

© Copyright IBM Corporation 2002, 2014

Figure 6-23. Calls in RPG IV AS068.1

Notes:
RPG IV can call other RPG IV programs as well as programs written in other languages such as
CL, COBOL, and C.
RPG IV gives you three different opcodes to call other programs (or ILE Modules) plus using
function execution.
The prototyped Callp opcode is discussed briefly here.

6-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Calling another program


IBM i

• Calling program (caller):


– Issues call to another program
– Passes parameters
– Parameters defined as prototype (PR)

• Called program (callee):


– Receives parameters
– Parameters defined as a procedure interface (PI)

• Parameter passing methods:


– By reference (address) is most common
– By read-only reference
– By value

© Copyright IBM Corporation 2002, 2014

Figure 6-24. Calling another program AS068.1

Notes:
Parameters must be defined in both the program that calls as well as the program that is called. The
normal way of passing parameters is accomplished by passing the addresses of the parameters.
Both the called and the calling program can access the same address for an individual parameter.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

The calling program


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-25. The calling program AS068.1

Notes:
1. The calling program contains a prototype (DCL-PR) for the called program. The called program
is next.
2. Notice in the call, the TotalBonus procedure is called. The procedure name is the same as the
name on the DCL-PR statement. When calling a procedure, the open and closed parentheses ()
are required even if there are no parameters passed. The Callp opcode could be used in front of
TotalBonus to identify this as a procedure call. Notice that the name of the PR might be different
from the actual name of the program (EXTPGM keyword). This is handy when you call system
routines or functions that sometimes are not named the as you want them to be named.
3. We are creating this program using the MAIN control option. This creates an inline program
without the old RPG cycle code. This makes the code more efficient and faster. Beside the
MAIN control word, we also declare the main procedure as a procedure using the DCL-PROC
statement.

6-32 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

The called program: Return to caller


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-26. The called program: Return to caller AS068.1

Notes:
Because you can call a program repeatedly, you may not want to set on LR after the called program
finishes. There is a way to leave the called program active.
When you return to the caller without turning on LR, the called program remains active. This is good
if you intend to call the program repeatedly. You do not pay the price of initializing the called
program more than once. This improves call performance.
The Return opcode returns control to the caller. In the example above, the caller is returned to
without setting LR on.
When you develop procedures that are called from other procedures, specifying the control option
keyword NOMAIN allows you to put multiple procedures in one source member. This is discussed
in the ILE programming sessions that you should have taken before this class.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Advantages of prototyping
IBM i

• Parameters are validated at compile time; runtime problems


are minimized.

• Prototypes tell the compiler to validate parameters:


– Number of parameters
– Data type and size
– Parameter type (reference, read only, value)

• Prototypes are easily held in separate members.


– Use /COPY to bring into programs:
• Can even store all prototypes in one copy member
• Compiler does not care about unreferenced prototypes

© Copyright IBM Corporation 2002, 2014

Figure 6-27. Advantages of prototyping AS068.1

Notes:
As stated, prototyping is designed to help you to catch errors at compile time when passing
parameters. The compiler validates that the prototyped parameters match the parameters passed
on the Callp opcode.
Many RPG IV programmers make a copy of the PI and change the PI to PR to create their
prototypes. These prototypes are stored in common libraries that other programmers can access
for using the prototypes in calling programs. In many cases, a programmer simply uses /COPY to
copy the prototype into the calling program.
Some shops even store prototypes as a group and the whole group is copied into the calling
program. The compiler does not care about unreferenced prototypes in a calling program.

6-34 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Options keyword for parameter definition


IBM i

• OPTIONS(*NOPASS):
– The parameter is optional.
– If any parameter is specified as *NOPASS, all subsequent parameters in
that prototype must also be *NOPASS.
• OPTIONS(*OMIT):
– The parameter can be omitted.
– The special value *OMIT is used on the Callp.
• OPTIONS(*VARSIZE):
– Applies to character fields and arrays only.
– The parameter can be smaller than specified in the prototype.
– It must be passed by reference (that is, no VALUE keyword).
• OPTIONS(*TRIM):
– It can be used with CONST or VALUE parameter.
– Leading and trailing blanks are removed.
– If not varying length, then it is padded with blanks on right (or left if
OPTIONS(*RIGHTADJ).
• OPTIONS(*RIGHTADJ):
– It can be used with CONST or VALUE parameter.
– Parameter value is right adjusted.

© Copyright IBM Corporation 2002, 2014

Figure 6-28. Options keyword for parameter definition AS068.1

Notes:
The OPTIONS keyword can be used in a prototype with a parameter. Its keywords provide more
facilities:
• *NOPASS: Means that the parameter does not have to be passed on the call. Any parameters
after this specification must also be described as *NOPASS.
When the parameter is not passed to a program or procedure, the called program or procedure
operates as if the parameter list did not include that parameter.
The called program can determine the number of parameters it received either by using
the %PARMS built-in function.
• *OMIT: Is used for parameters that are not mandatory but that occur in the middle of a
parameter sequence. Therefore, they cannot be designated as *NOPASS.
When the *OMIT option is specified, the special value *OMIT is specified instead of that
parameter on the call.
The *OMIT parameter is counted in the number of parameters that are passed and the called
program needs to test to see whether the parameter was passed. Any attempt to reference the

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

parameter when *OMIT was passed results in an error. There are two ways to test to see
whether the parameter was passed:
- Compare the %Addr of the parameter to *Null. This cannot be used if the parameter was
designated as CONST.
- Use the API CEETSTA.
The RPG Programmers Guide provides a brief example in Chapter 10, “Calling Programs
and Procedures.”
*OMIT is only allowed for parameters that are passed by reference, including the ones that
specify the CONST keyword.
• *VARSIZE: Tells the compiler to accept a character parameter that is shorter than the prototype
specifies. Effectively, it indicates that the length specified is to be treated as a maximum.
This option is often used when the length of the passed field is also passed to the called
program (for example, QCMDEXC).
• *RIGHTADJ: When specified for a CONST or VALUE parameter in a function prototype, the
parameter value is right adjusted. This keyword is not allowed for a varying length parameter
within a procedure prototype.
• *TRIM: When specified for a CONST or VALUE parameter of type character, the passed
parameter is copied without leading and trailing blanks to a temporary work variable. If the
parameter is not a varying length parameter, the trimmed value is padded with blanks (on the
left if OPTIONS(*RIGHTADJ) is specified; otherwise, on the right). Then, the temporary is
passed instead of the original parameter.

6-36 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Setting *INLR
IBM i

• End of calculations and LR set *ON


• RETURN with LR set *ON:
– Variables cleared
– Files closed
– Slower program activation

• RETURN with LR set *OFF:


– Variables left intact
– Files left open
– Re-entrant program coding required
– Faster program activation

© Copyright IBM Corporation 2002, 2014

Figure 6-29. Setting *INLR AS068.1

Notes:
We saw how one RPG IV program can call another. We also saw two methods for ending a
program and returning to the caller.
This visual summarizes the two methods for ending a program.
Particular consideration needs to be given to passing information between programs. There are
many techniques for passing information between programs. The most common way of passing
information is using parameters.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

What is a subprocedure?
IBM i

• Subprocedure is the RPG IV name for user-defined procedure.


– Evolution of subroutines

• Subprocedures can:
– Define their own local variables
• Only the code associated with the variable can change its content.
– Access global variables defined in the main body of the source
– Access any files defined in the program
– Be called recursively

• The compilation unit can have any number of subprocedures.


– Each subprocedure must have its own prototype.

• Compilation unit is source code processed by the compiler in a


single compilation.
– Includes any /COPY members
© Copyright IBM Corporation 2002, 2014

Figure 6-30. What is a subprocedure? AS068.1

Notes:
A subprocedure could be perceived as the modern version of the subroutine. However, whereas
subroutines are always local to a specific program, subprocedures can be used and called by many
programs.
Before we discuss subprocedures further, we should define the term procedure. A procedure is the
RPG IV name for what we commonly call a program. We refine this definition when we cover ILE
but at this point, think of a procedure as a type of program.
A subprocedure is a subprogram that is contained within a procedure or packaged in an ILE
Service Program. An RPG IV subprocedure is the logical evolution of an RPG subroutine.
User-written subprocedures in RPG IV allow recursion. Recursion means that a subprocedure can
repeatedly call itself, directly or indirectly, within a job stream. Subprocedures support local
variables; that is, fields that are defined within a subprocedure, and are only available to and
affected by logic within the bounds of the subprocedure.
RPG IV subprocedures use prototypes. In this topic, we use prototypes in RPG IV subprocedures.
However, you find later that many of the same prototype-writing skills can be applied to access
system APIs and C functions.

6-38 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty By compilation unit, we include the RPG IV source that can be successfully processed by the RPG
compiler. In RPG IV, each compilation unit is compiled into a module (*MODULE) object. Several
modules can be grouped into a single program.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-39
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Writing code for subprocedures


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-31. Writing code for subprocedures AS068.1

Notes:
Notice the sequence of the specifications that are in the visual. In this example, the subprocedure is
coded in line after the main procedure. The main components of the process are seen in
subsequent visuals.
In summary:
• The prototypes for the subprocedure are coded first. The main procedure calls the
subprocedure. Therefore, a PR that matches the PI for the subprocedure is required.
• Dcl-proc marks the beginning of the main procedure and inline subprocedure.
• Procedures appear after the regular C specs. We look in more detail at the sequence of
specifications in this “new style” of RPG program later.
• The D-specs for fields that are used only by the subprocedure are coded next.
The two fields with an S (stand-alone fields) are local variables available only to the logic in this
particular subprocedure.
• The logic functions performed by the subprocedure are coded next.
• A Return is coded in order to pass control back to the caller of the subprocedure.

6-40 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • An END-PROC is coded in order to end the subprocedure. The END-PROC designates the end
of the subprocedure. The END-PROC does not have to have the corresponding procedure
name but it is a good programming practice to include it.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-41
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Different types of RPG IV source members


IBM i

• Traditional style
– Main line only
– Uses RPG logic cycle
– May include subroutines or subprocedures

• RPG IV main + subprocedures:


– Main procedure:
• Global files and global variables defined outside procedure
• Uses MAIN keyword and prototypes
– Local subprocedures:
• Can define their own (local) variables
• Can define their own (local) files
• Can access (global) variables
– No RPG logic cycle

• RPG IV subprocedures only (recommended)


– Main section can define files and variables but no logic:
• No main procedure; NOMAIN keyword
• No RPG logic cycle
© Copyright IBM Corporation 2002, 2014

Figure 6-32. Different types of RPG IV source members AS068.1

Notes:
When you want to use the features of subprocedures, you have two choices:
1. You can include the subprocedure code in the same source member as the mainline code that
calls it.
When you do include subprocedures in the same source member as the mainline, you code a
single main procedure, followed by one or more subprocedures. The main procedure defines all
files and global data. Global data items are usable by any subprocedures in the same module.
Fields in files that are defined in the mainline are always considered global. You can define a file
in a subprocedure that would be local.
2. You can place your subprocedures in a separate module using the cycle-less support that is
mentioned in the visual. Subprocedures can be grouped as single or multiple subprocedures in
a NOMAIN procedure.
This is the recommended method of coding subprocedures. They are packaged in a much more
modular fashion. They are easier to maintain and to modify. They can be easily called by those
programs that you authorize to access them.

6-42 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty RPG IV subprocedures must be coded specifying no logic cycle (cycle-less). This is because
the RPG cycle code is not generated by the compiler because it is for all RPG IV modules with
a mainline. The benefit of cycle-less coding is that calls to subprocedures in these cycle-less
modules are fast because there is no logic cycle overhead.
When you first try to create subprocedures, you may receive the compiler message:
RNF3788 - Keyword EXTPGM must be specified when DFTACTGRP(*YES) is specified on the
CRTBNDRPG command.
You may receive this message because the default values on the CRTBNDRPG command assume
that the type of compilation you want is for an OPM program.
Subprocedures are a part of the ILE environment. If you are using subprocedures, you are using a
feature of ILE. The default values must be changed. With the RDi LPEX editor, you can change the
defaults for the command on your PC and leave the default on the IBM i as-is.
Compiling with Subprocedures
You must compile with the option DFTACTGRP(*NO).

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-43
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Major features of subprocedures


IBM i

• Compilation unit can contain many subprocedures.


• Subprocedures can:
– Be called from an expression
– Call other subprocedures
– EXSR to inline subroutines in subprocedure
– Return parameters
• Subprocedures cannot:
– Contain coding of other nested subprocedures
– EXSR to subroutines in a MAIN procedure
• Subprocedures can return a value:
– Called like a function, such as RPGIV BiFs

© Copyright IBM Corporation 2002, 2014

Figure 6-33. Major features of subprocedures AS068.1

Notes:
Subprocedures that return a value can be used in a manner similar to RPG IV built-in functions, as
shown in this example. In this example, the subprocedure DayOfWeek is called, which requires a
single input parameter.
1. In the first line of code in the visual, the parameter is the field named ADateFld.
2. In the second line of code, the parameter is the field Today.
DayOfWeek returns a value, the day of the week (1 - 7) representing Sunday through Saturday.
The returned value replaces the function call in the statement. In the second line of code, the
returned value is placed in the field WeekDay.
Notice the use of a subprocedure in a free form expression.
The free form call statement, Callp (Call with Prototype), can be used to invoke any subprocedure
that does not return a value. It is not recommended to code the Callp.

6-44 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

What are local variables?


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-34. What are local variables? AS068.1

Notes:
Any subprocedures that are coded inline within the source member that contains the main
procedure automatically can access global data items that are defined in that main procedure.
These subprocedures can also include Data definitions of their own local data fields. These local
data fields are accessible only within the subprocedure in which they are defined.
In the example, the prototypes and parameters are not shown. Focus your attention on local versus
global variables.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-45
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Basic subprocedure
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-35. Basic subprocedure AS068.1

Notes:
This is a further refinement of the subprocedure shown earlier, based on the subroutine. The
recommended practice of coding /COPY to bring in the prototype code is used here.
The /COPY DOWPROTO line of code copies the source member that contains the prototype code.
Once again, the subprocedure is coded in-line after the main procedure. Here is a reminder of the
sequence of specifications:
3. The prototypes for the subprocedure are coded first. The main procedure calls the
subprocedure. When the subprocedure is local to the procedure, a prototype is not required.
Any global Definition specs are before the calculation specs of the mainline.
1. Call the subprocedure from an expression (like a BiF).
2. The DCL-PROC specification that begins the subprocedure appears after the regular
calculation specs. We look in more detail at the sequence of specifications in this new style of
RPG program later.
The Definition specs for fields that are used only by the subprocedure are coded next. The DayNo
variable from the earlier example is no longer needed because the result is returned on the Return
operation (explained later).

6-46 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty 3. The two fields with a DCL-S (stand-alone fields) are local variables available only to the logic in
this particular subprocedure. The constant (DCL-C) field is also only used locally so defined
here.
The logic for the subprocedure is next.
4. A Return to the Caller. This statement is mandatory in this example because a value is returned
from the subprocedure to the caller.
An END-PROC spec to end the subprocedure. The name of the subprocedure is not required but
helps to identify the procedure name and is good programming practice.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-47
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Invoking the subprocedure


IBM i

Call to DayOf Week subprocedure is BiF-like.


Field InputDate is passed as a parameter to the subprocedure.

© Copyright IBM Corporation 2002, 2014

Figure 6-36. Invoking the subprocedure AS068.1

Notes:
1. A subprocedure is called in much the same syntax as you call a built-in function in RPG.
Because this subprocedure returns a value, it is called from an expression. The returned day
number value is placed in the field DayNumber.
If the subprocedure was not coded to return a value, it could be invoked with a Callp or just the
subprocedure name followed by any parameters.

6-48 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Procedure specs and the procedure interface


IBM i

• Subprocedure delimited by Procedure specs


– Fixed form has P in column 7
• B(egin) names the procedure
• E(nd) required to complete it
– Free form has DCL-PROC and END-PROC
• End with semi-colon (;)

• Procedure interface that is required


– PI optionally defines data type and length of return value
– Code that follows define any parameters
• Parameters that are terminated by end-pi or non-blank entry in columns 24-
25 of fixed form Definition Spec
The procedure name is optional on
both the PI and the END-PROC
Spec

© Copyright IBM Corporation 2002, 2014

Figure 6-37. Procedure specs and the procedure interface AS068.1

Notes:
Subprocedures begin with a Procedure spec and must be terminated by an end Procedure spec.
In this example, you can see both the beginning dcl-Proc spec and the ending end-Proc spec.
The next thing that is needed is a Procedure Interface, or PI. The procedure interface defines the
interface to the procedure the parameters passed to the subprocedure from the subprocedure, or
both. The PI is defined with the dcl-pi and end-pi specs. These are typically the first lines of code in
the subprocedure.
The data item that is defined on the same line as the dcl-PI is the return value.

Note

It is possible to have a subprocedure that returns no value. A subprocedure can return, at most,
one value.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-49
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

The data items between the dcl-PI and end-pi are the parameters to the subprocedure. In this
example, the InpDate field is the only parameter.

6-50 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Returning the result


IBM i

• Can return a simple value:

• Can return an expression:

© Copyright IBM Corporation 2002, 2014

Figure 6-38. Returning the result AS068.1

Notes:
Here the return value for this subprocedure is specified. The RETURN operation code with a return
value is used.
The returned value can be either a single field or an expression, as in the second example. In fact,
because a subprocedure can be used anywhere a variable of its type can be used, the returned
value itself could be the result of a subprocedure invocation. But recursion is not discussed here.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-51
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Defining the prototype


IBM i

• Required in caller for each subprocedure called

• Almost identical to PI

• Used to validate parameters during compile

• Create from PI

• COPY into procedure

© Copyright IBM Corporation 2002, 2014

Figure 6-39. Defining the prototype AS068.1

Notes:
The next step is to define the prototype. As discussed earlier, the parameters in the prototype must
match the Procedure Interface because it defines the interface to the procedure.
The prototype is used by all procedures that call this subprocedure. The prototype must also be
coded in the module where the procedure is defined. This is done so that the compiler can check
the validity of the prototype; that is, it checks that the parameters specified match the Procedure
Interface in parameter number and type. If the subprocedure is placed in the same source member
as the caller (as in this example), only a single copy of the prototype is required, because the
compiler is able to check the prototype and procedure interface in a single compile step. If the
subprocedure were to be placed in a separate source member, then a copy of the prototype would
be required in both the member containing the subprocedure and in the main procedure (or calling
procedure) as well as in any other main or subprocedures calling this subprocedure.
A common, and encouraged, practice is to place the prototypes for subprocedures in a separate
source member that is copied in using the /COPY directive. This is especially important if the
subprocedure is coded as a separate source member and then created as a separate module. The
prototype in the calling procedure must match the one in the defining procedure. This prototype is
the one in the module that contains the subprocedure that the compiler verified for you.

6-52 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Subprocedures calling other subprocedures


IBM i

• For a specific date, determine day ("Monday", "Tuesday", and


so forth)

© Copyright IBM Corporation 2002, 2014

Figure 6-40. Subprocedures calling other subprocedures AS068.1

Notes:
This visual illustrates how subprocedures can call other subprocedures. The new DayName
subprocedure calls the DayofWeek procedure to get the number of the day of the week. The
DayName procedure then translates the number into a day name.
The /COPY member for the prototypes in this case would need to include a prototype for DayName
and one for DayofWeek because DayName calls DayofWeek.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-53
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Machine exercise: Procedures


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-41. Machine exercise: Coding procedures AS068.1

Notes:
Perform the Procedures machine exercise.

6-54 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Subroutines
IBM i

• Modular way of writing your code


• Placed at the end of calculations
• Local: Can be executed only within program in which they are
located
• Calculations that are used repeatedly in your program

© Copyright IBM Corporation 2002, 2014

Figure 6-42. Subroutines AS068.1

Notes:
Using subroutines allows you to organize your code in a more readable as well as a modular
fashion.
How to code a subroutine and then all the ways they can be executed from within an RPG IV
program with the EXSR opcode is covered.
Subroutines are local to the program in which they are coded, and they cannot be called from
outside that program. If the code has universal application, a procedure should be written instead.
That is why we prefer coding subprocedures rather than subroutines. We review subroutines here
because you will see them in older, legacy code.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-55
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Coding subroutines
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-43. Coding subroutines AS068.1

Notes:
In this visual, the subroutine DayOfWeek is shown. The DayOfWeek label is used to call the
subroutine with the EXSR opcode. This is the same procedure as we saw before. Coding this as a
subprocedure to start makes it more versatile than using it as a subroutine that is limited to one
place.
A subroutine is a set of RPG calculations that are enclosed within BEGSR and ENDSR operation
codes. On the BEGSR statement, you must code a subroutine name to uniquely identify this
subroutine within this particular program. You can code as many subroutines as you want in a
program.
All subroutines within your program must be grouped at the end of your calculations. You can code
only one subroutine between each set of BEGSR and ENDSR opcodes. Subroutines cannot be
coded in a nested fashion. However, one subroutine can issue an ExSR to execute another
subroutine.
The code example shows the traditional use of a standard subroutine, including its inherent
problems. WorkNum and WorkDay are standard field names within the subroutine that referenced.
They are defined in the main procedure yet used as local work variables within the subroutine.

6-56 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty InputDate and DayNumber are being used as if they are parameters. This is a good practice for
isolating the mainline logic from the subroutine logic.
The use of subroutines forces the use of naming standards to ensure that work fields within the
subroutine do not get used in the mainline logic. However, all variables are defined globally for the
program. Only coding conventions and standards enable the isolation of the scope and use of
certain variables. These conventions cannot be enforced, and might easily be overlooked or
ignored during later maintenance.

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-57
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Execution of a subroutine
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-44. Execution of a subroutine AS068.1

Notes:
The ExSR opcode causes a branch directly to the named subroutine. Upon completion of the
subroutine, your program returns to the calculation specification immediately following the ExSR
opcode. The ExSR opcode can occur anywhere in the code.

6-58 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Implicit execution of a subroutine


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 6-45. Implicit execution of a subroutine AS068.1

Notes:
Subroutines can also be executed implicitly if they are identified as special routines, such as *InzSR
(initialization subroutine).
The initialization subroutine allows the calculations in the *InzSR to be run before anything else in
the program. A specific subroutine that is to be run at program initialization time can be defined by
specifying *InzSR as the name of the subroutine beside the BegSR operation. Only one subroutine
can be defined as an initialization subroutine. It is called at the end of the program initialization step
of the program cycle. Briefly initializing fields, opening files, and so forth is included.
It is not necessary to code the ExSR for the *InzSR subroutine as it is executed by the system
automatically (only once).
Reference:
ILE RPG Language Reference, RPG Program Cycle, and other implicit Logic

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-59
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Checkpoint
IBM i

1. True or false: The parameter list in both the calling and the
called programs must match field name by field name.

2. Which of the following opcodes does not have a


corresponding Endxx statement to terminate the group?
a. Do
b. If
c. Plist
d. BegSR
e. Select

3. True or false: An RPG subroutine can be called from another


program outside of where it is written by coding an ExSR.

© Copyright IBM Corporation 2002, 2014

Figure 6-46. Checkpoint AS068.1

Notes:

6-60 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Unit summary
IBM i

Having completed this unit, you should be able to:


• Write structured RPG IV code
• Write RPG IV code with conditional If, DoW, DoU, and For
opcodes
• Write RPG IV code with conditional Select groups
• Determine the number of nesting levels for a nested group
• Describe how to use the %Error and %Status BiFs with the
error (E) extender
• Write code for a subprocedure in an RPG IV program
• Describe the usage of subroutines in older RPG IV programs

© Copyright IBM Corporation 2002, 2014

Figure 6-47. Unit summary AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 6. Structured programming, error handling, subprocedures, and 6-61
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

6-62 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 7. Using arrays, data structures, and data
areas

What this unit is about


This unit describes how to define and use arrays in RPG IV. It also discusses
the RPG tables briefly.

What you should be able to do


After completing this unit, you should be able to:
• Define an array in an RPG IV program
• Use the %LookUpxx and %Xfoot BiFs
• Define a data structure in an RPG IV program
• Name two types of data structures and explain how they would be used
• Define a multidimensional array in an RPG IV program
• Use the Like and LikeDS keywords
• Use Qualified Data Structures
• List one use of a data area
• Define a data area in an RPG IV program

How you will check your progress


• Checkpoint questions
• Machine exercise
- To an existing program, the students add RPG IV code to define and
process arrays.
• During this exercise, the students add RPG IV code to:
- Define a compile-time array
- Store and access data in array elements
- Access array elements using an index

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:

• Define an array in an RPG IV program

• Use the %LookUpxx and %Xfoot BiFs

• Define a data structure in an RPG IV program

• Name two types of data structures and explain how they would be used

• Define a multidimensional array in an RPG IV program

• Use the Like and LikeDS keywords

• Use Qualified Data Structures

• List one use of a data area

• Define a data area in an RPG IV program

© Copyright IBM Corporation 2002, 2014

Figure 7-1. Unit objectives AS068.1

Notes:

7-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

What is an array?
IBM i

• Assume we have a set of 12 fields, named SALES.


• Each individual field holds sales for a specific month.
• Each field is numeric, 8 digits, two decimals.
Total Sales
Month
by Month
January 125876.15 (1)st element
February 78421.12 (2)nd element
March 2248334.87 (3)rd element
April 245453.15 (4)th element
May 312585.35 (5)th element
June 299542.76 (6)th element
July 342664.01 (7)th element
August 376012.00 (8)th element
September 357886.12 (9)th element
October 423998.67 (10)th element
November 422554.23 (11)th element
December 456334.12 (12)th element
© Copyright IBM Corporation 2002, 2014

Figure 7-2. What is an array? AS068.1

Notes:
An array is a contiguous set of data elements that are the same length and data type. Each
element can be accessed using a numeric value, called an index, which is combined with the array
name. You can address a unique element or the complete array.
If the name of the set of data in the visual was SALES, we could work with the data for June by
addressing SALES(6). The 6 is the index to the SALES array. The index can be a numeric literal or
a variable. You can write a single line of code and loop through varying values of the index rather
than process a number of sequential lines of code that are the same except for the address of the
variable.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Processing data in an array


IBM i

• Field by field:

• Using an array:

© Copyright IBM Corporation 2002, 2014

Figure 7-3. Processing data in an array AS068.1

Notes:
Using an array can mean fewer lines of code. In this case, we assume that the JanSales through
DecSales fields are defined in a database file. Using Mon as the index to the array (where Mon
varies from 1 - 12), we add the value of each element of the array SALES.
Our alternative, and we exaggerate in the example, is to code an expression to add each
mmmSALES field into the accumulator TotSales.

7-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Summary of Definition spec keywords for arrays


IBM i

Keyword Description
Dim(number) Number of elements in array
Ascend/Descend Order of elements in array
Perrcd(number) # elements for compile time table/array
FromFile/ToFile From/To file for pre-run time array/table
ExtFmt External data type for compile and pre-run time arrays
Alt(array_name) Compile/preruntime array alternating format
CtData Indicates compile time data

© Copyright IBM Corporation 2002, 2014

Figure 7-4. Summary of Definition spec keywords for arrays AS068.1

Notes:
Arrays are defined with a Definition specification. This visual highlights the keywords that are
associated with the definition of arrays.
In this visual, note the following points:
• The DIM keyword identifies the stand-alone fields Array1 and Array2 as arrays. Note both are
one-dimensional arrays. You might be familiar with the term vector. These are vectors.
• The maximum number of elements or the total size of an array allowed is 16,773,104. The
total size of the array (all of its elements) cannot exceed 16,773,104 bytes. This is a system
limitation that is established at V6.1 of IBM i.
• Arrays can be loaded with data in three different ways:
- Compile time: The data is included with the source program. The CtData keyword is used
to specify that data is included with the source program. This is not recommended as a
‘best practice’. In future visuals, we will see a better way to define compile time arrays.
- Pre-execution time: The data is loaded from a file that is to be read at program
initialization.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

- Execution time: The data is loaded from records in a data file as requested by the program.
This is the most common way of loading data.
• Array2 is loaded at compile time. Notice the CtData keyword. Also, notice it again at the end of
the source program. The data for the array follows the ** CtData Array2 statement. This
identifies the data as belonging to Array2. The Perrcd keyword is used to specify how many
array elements are included per record (in this case, source record).
The type of array that you use depends on the volatility of your data. If the data is fixed and never
changes, you can use compile time or pre-execution arrays.
Notice that if the data in a compile time array ever changes, you have to update the array using RDi
and then recompile your program. So, don't place information such as sales tax or income tax
information in a compile time array!
For your reference, other keywords are documented below:
• Ascend or Descend: They are used to specify if the array is sequenced.
• ToFile: If you want to write out the array to a file at EOJ, specify ToFile. The data is written at LR
time.
• FromFile: It is used to specify the name of the file that contains the data for the pre-execution
array.
• ExtFmt: It is used to define the format of the data in the data record (for example, B=binary,
S=signed numeric, I=integer).
• Alt: Alternating sequence is to be used.
Finally, for compile time arrays, at the end of your RPG source you code one **CtData statement
for each array followed by its data. It is not mandatory to include the array name beside the
**CtData but it is good practice. If you use **CtData array_name, you must do so consistently for
the program. If you do not specify the array_name, the compile time arrays are loaded with data
based on the order in which they are defined on the Definition specification.
You must not mix these methods. The compiler does not allow it.

7-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Compile time load


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-5. Compile time load AS068.1

Notes:
Rather than using the CtData keyword and having to go to the bottom of the source to find the data,
a data structure is defined. The sales array is specified at the end starting with the first position in
the data structure. While using more space than CtData with Perrcd, this code is easier to read and
maintain. We will learn more about data structures later in this unit.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Naming arrays
IBM i

ARRAYS

Name can be any valid RPG name

Index used to address elements


Index can be literal / variable
SALES(MON)

Compile, pre-run or execution fill

Search with %LookUpxx

© Copyright IBM Corporation 2002, 2014

Figure 7-6. Naming arrays AS068.1

Notes:
Arrays can be named anything that you want if it is a valid RPG IV name. When you consider a
name for the array, remember that you reference individual elements and need to allow space for
the parentheses and the index variable name. Some examples are:
• Sales(Mon): An array of 12 elements (Mon = 1 - 12). Remember the index cannot be greater
than 12. Nor can it be zero or negative when you are processing the Sales array. If the index
is zero or negative, you get an execution time error and control is passed to the RPG IV Default
Error Handler.
• QtyAv(Loc): Inventory quantity available for shipment from nine warehouse locations. Loc is a
numeric variable varying from 1 - 9.

7-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Moving array data


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-7. Moving array data AS068.1

Notes:
Here are some examples of ways to move data in and between arrays.
• As usual, the data types must match on both sides of the equal
• You can have different length on both sides of the equal but be careful of truncation of character
data or numeric overflow
• You can also have arrays of different sized on both sides of the equation
• You can also use the EvalR opcode to right adjust character data
• The elements are operated on one by one until either of the arrays runs out of elements.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Crossfooting arrays
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-8. Crossfooting arrays AS068.1

Notes:
%Xfoot sums all the elements of an array together and places the sum into the accumulator field
that is specified in the result field.

7-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Using arrays in a loop


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-9. Using arrays in a loop AS068.1

Notes:
Notice how simple it is to operate on arrays. With a few lines of code, we can determine the profit by
month for the past 12 months. This is a simple example but imagine the coding that would be
necessary without arrays.
Notice that the half adjust operation extender (H).

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

%LookUpxx
IBM i

%LookUpxx(arg:array{:startindex})
%LookUp: Searches for an exact match
%LookUpLE: Searches for either an exact match,
or the highest item lower than arg
%LookUpLT: Searches for the closest item lower
than arg
%LookUpGE: Searches for either an exact match,
or the lowest item higher than arg
%LookUpGT: Searches for the closest item greater
than arg
• Successful match returns index value; 0 = unsuccessful.
• arg and array can be of any type, but they must match.
• startindex must be a non-float numeric with 0 decimals.
• For %LookUpxx, the array must be defined with Ascend or
Descend.
© Copyright IBM Corporation 2002, 2014

Figure 7-10. %LookUpxx AS068.1

Notes:
This visual shows the features of %LookUpxx for arrays.
There is a fourth parameter that you can use that tells the BiF at which element to stop searching.
%LookUp(arg :array {:startindex {:numelems}})
Using the %LookUpLT, %LookUpGE, or %LookUpGT requires that the array be sorted. We look
at how to do this soon.

7-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

%LookUpxx example
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-11. %LookUpxx example AS068.1

Notes:
This is an array application. Suppose that we have an application where we must determine the
rate of tax that is based on an amount. The greater the amount, the higher the tax rate.
The %LookUpxx BiF searches the array that is based on the search argument, which is the first
parameter. The search argument is matched to the array in the second parameter. The type of
search depends on the suffix of the %LookUpxx BiF. In this case, we have the array (ArrAmt)
organized such that we want to match the array element that is less than or equal to the search
argument.
In this example, we search the array sequentially, element by element until we find the element of
the array ArrAmt that is equal to or lower than the value of PayAmt. When %LookUPLE has a
match (Indx > 0), we know that the corresponding element of ArrRate has the tax rate that we must
apply. You reference the array element in ArrRate by using the array name, ArrRate(Indx), in
subsequent code as wanted. The value of the Indx field that points to ArrAmt and ArrRate remains
the same until the next search using %LookUpLE is performed.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Here are the elements of the two arrays, ArrAmt and ArrRate and the corresponding values of
PayAmt:
PayAmt ArrAmtArrRate
0.00 - 99.99 00.10
100.00 - 199.991000.12
200.00 - 499.992000.15
500.00 - 999.995000.18
1000.00 - 9999.9910000.20
This is an example of how the %LookUpxx BiF can be used with an array. For several values of
PayAmt:
• If PayAmt = 150.00, then ArrAmt points to the second element and we use ArrRate(2), that is,
0.12
• If PayAmt = 997.00, then ArrAmt points to the fourth element and we use ArrRate(4), that is,
0.18
Notice that the two arrays overlay a data structure. We discuss overlay and position later in this unit.
This means of loading data works well if the data is stable in nature (such as day number/day of the
week or month number/month of the year). For a tax application, we would normally load the data
from a file at pre-execution time.

7-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

SortA
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-12. SortA AS068.1

Notes:
SortA is an opcode that can be used to sequence your array. If sequence was defined on the
Definition spec, the elements are sorted into that sequence. If no sequence was specified, then
ascending is assumed.
In the visual, the SortA would produce an array of amounts that are sorted from smallest to largest.
Ascending sequence is assumed because we did not specify any sequence on the Definition spec.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

BiFs and arrays: %Size


IBM i

%Size(name{:*ALL})
z Returns storage size (in bytes) occupied by the named item

© Copyright IBM Corporation 2002, 2014

Figure 7-13. BiFs and arrays: %Size AS068.1

Notes:
As you can see from this example, built-in functions can be used in calculations as well as on the
Definition spec.
When used on the Definition spec, the value of the %Size built-in function is determined at compile
time and the argument cannot be an expression.
The *all option of the %Size BiF is used with arrays. If *all is specified as the second parameter
for %Size, the value that is returned is the storage that is taken up by all elements or occurrences.
If you are working with an array and do not specify *all, the size of a single element is returned.

7-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

BiFs and arrays: %Elem


IBM i

%Elem(name)
z Returns number of elements in an array or table

© Copyright IBM Corporation 2002, 2014

Figure 7-14. BiFs and arrays: %Elem AS068.1

Notes:
The %Elem is similar to the %Size function and its benefits in maintenance are the same as those
for %Size.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

BiFs and arrays: %SubArr


IBM i

%SubArr(name:start-index{:number-of-elements})
z Get or set a section of the specified array

© Copyright IBM Corporation 2002, 2014

Figure 7-15. BiFs and arrays: %SubArr AS068.1

Notes:
The built-in function %SubArr returns a section of the specified array starting at start-index. The
number of elements returned is specified by the optional number-of-elements parameter. If not
specified, the number-of-elements defaults to the remainder of the array.
%SubArr can be used in the following ways:
• On the left side of an assignment using Eval or EvalR. This changes the specified elements in
the specified array.
• Within the expression on the right side of an assignment using EVAL or EVALR where the target
of the assignment is an array.
• With the SortA operation.
• As the parameter of the %Xfoot built-in function.

7-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Characteristics of data structures


IBM i

• Occupy storage
• Program described or externally described
• Redefines storage
• Internal
• Character string
• Programmer controls arrangement of data

© Copyright IBM Corporation 2002, 2014

Figure 7-16. Characteristics of data structures AS068.1

Notes:
A data structure is an area in program storage that can be used to define the layout of subfields
within that area. It can be program described or externally described.
This visual lists some of the characteristics common to data structures:
• They occupy storage just like all other data.
• They are created during program initiation and deleted when the program ends.
• The data in a data structure is available only to the program that creates it.
• A data structure permits an RPG IV program to redefine a portion of its variable space. This is
not the same as defining fields as we have previously because each field is assigned a
separate storage area, even if more than one field is filled from the same part of a database
record. For example, if the date is retrieved into a field as DATE and also as MO, DAY, and YR,
four separate areas are formatted to hold the data. If it is retrieved into a data structure, only one
area is assigned and the data is simply reformatted.
• The program treats the data structure as a character string, even if one or more subfields are
defined as numeric.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Types of data structures


IBM i

• Basic
• Array
• Data area
• Program status
• File information

© Copyright IBM Corporation 2002, 2014

Figure 7-17. Types of data structures AS068.1

Notes:
Basic, array, and data area types of data structures are covered in this unit.
The program status and file information data structures are often used to handle exceptions and
were mentioned briefly in the “Structured programming, error handling, subprocedures, and
subroutines” unit.

7-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Defining data structures


IBM i

Keyword Definition
Inz(constant) Initialize to value of constant
Overlay(name:{pos}) Redefines subfields in a DS
Pos(starting-position) Redefines subfields in a DS
ExtName(name{:fmt_name}) File name for externally described DS
ExtFld(fldname) External field name being renamed
Prefix(prefix{nbr_of)char_replaced}) Prefix subfields from externally described DS
Len(number) # defining length of field

© Copyright IBM Corporation 2002, 2014

Figure 7-18. Defining data structures AS068.1

Notes:
Data structures are defined in your program using the Dcl-ds/End-ds structure.
Notes:
• Indented subfield names enables us to show the construct of the data structure clearly and to
make the code readable.
• The entire Data Structure is initialized to blanks or zeros, except Status, which is initialized to R.
• AreaCode overlays the first three positions of PhoneNumber (positions 31-33 of the Data
Structure).
• LocalNumber overlays the last seven positions of PhoneNumber (positions 34-40 of the Data
Structure).
• Using Overlay to subdivide or redefine fields is recommended because the maintenance of
your code is easier and less error prone.
• The Inz keyword can also be used to initialize stand-alone fields and overrides the Inz at the
Data Structure level.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

The rules for using Overlay are:


• Field that is overlaid must be a subfield that is previously defined in this Data Structure.
• Optional positions parameter (see the second Overlay in the visual) can be a numeric literal, a
numeric named constant, or a built-in function.
• Length notation must be used on the overlaying field.
• If an array is overlaid, the Overlay keyword applies to each element of the array.
Remember packed numeric fields defined on the Definition spec have length defined in terms of
digits versus the storage that is required in bytes. The default numeric type for data structures is
zoned decimal, unless explicitly defined otherwise.
The end of subfield definitions is indicated with the End-ds definition or, for fixed format definitions,
the definition of stand-alone fields or arrays. In this example, myData and myData2 are fields that
are not part of the data structure. With V6.1 of IBM i, RPG IV can now have data fields that are
defined as large as 16,773,104 bytes.
Finally, note that a data structure is a character string; so it contains blanks by default. Failure to
explicitly initialize all subfields to zero or blank before using them can cause decimal data errors for
numeric subfields.

7-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Externally described data structure


IBM i

• For externally described files only


• No File spec declaration required

© Copyright IBM Corporation 2002, 2014

Figure 7-19. Externally described data structure AS068.1

Notes:
Some advantages of an externally described data structure include:
• Maintains integrity of your data definitions
• Reduces the coding that is required
In a program, there is no functional difference between a program described and an externally
described data structure. An externally described data structure may also be the description of a
database file, so it can help to maintain the integrity of data definitions.
If a data structure is to be used in multiple programs, externally describing it can reduce the coding
that is required. The data structure can be described once, and then referenced whenever it is
needed. This can be useful when a data structure is used to pass a parameter list between
programs.
Three steps are required to externally describe a data structure:
1. The first step is to describe DDS for a physical file. The DDS must exist.
2. The second step is to create the physical file. Again it must exist, and the file may or may not
contain data. This file description becomes the external description of the data structure. When

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

the physical file is created, if the member parameter is *NONE, there are no data members
associated with it, and the format can be used as a data structure.
3. In step number three, the program describes the data structure by referencing the physical file
name on the Data Definition Specifications. For fixed form the data structure name is entered
starting in column 7 and a DS in the Ds columns identifies this as a data structure. The E in
column 22 indicates that it is externally described, and the name of the physical file that
supplies the description is supplied as a parameter of the ExtName keyword (the format name
is optional). For free-form, the data structure name appears after the DCL-DS. The ExtName
keyword is used it identify the file and format. The End-ds followed by a semi-colon ends the
data structure.

7-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Uses for data structures


IBM i

Group fields

Subdivide fields

Enhance function of
arrays

Redefine fields

© Copyright IBM Corporation 2002, 2014

Figure 7-20. Uses for data structures AS068.1

Notes:
The visual summarizes some uses of data structures:
• Group fields: The fields may be from one or more input records and are not contiguous.
• Subdivide fields: You can break up a field into component parts, for example, a field called
FullName into FirstName and LastName.
• Arrays: When defined as part of a data structure, we can create arrays of more than a single
dimension (a matrix).
• Redefine fields: You can use a data structure to redefine fields with other names (and
restructure).

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Qualified names and templates


IBM i

DsName.SubFldName
• Simple qualified name
Ds1Name.Ds2Name.Ds3Name.SubFldName
• Compound qualified name

• Qualified keyword on DS
• Template keyword on DS
• LikeDS keyword to define one DS like another DS
• LikeDS with DS also says Qualified
• Subfields in several DSs can have the same names
© Copyright IBM Corporation 2002, 2014

Figure 7-21. Qualified names and templates AS068.1

Notes:
This visual overviews the features of qualified naming.
Qualified naming allows us much more flexibility. Subfields in two different data structures can have
the same names with different attributes. Templates are use to defined data structure that has no
storage associated at runtime.

7-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Qualified Template and LikeDS: Example


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-22. Qualified Template and LikeDS: Example AS068.1

Notes:
This example illustrates the use of the LikeDS and Qualified and Template keywords for data
structures.
• The CustTmpl and Part data structures are Qualified Templates. Thus references to subfields
must use the qualified naming format as shown. These structures may not be used directly in
the program. Notice that these two DSs have a subfield with the same name.
• The Cust, Part1 and Part2 data structures are secondary data structures. They need only the
LikeDS keyword and no Qualified keyword. Because its subfields are named the same as
those of the templates from which they are derived, qualified naming is mandatory and the
Qualified keyword is not required.
• In calculations, you must reference the data structure fields using qualified names or you get an
error.
The Part3 data structure is an example of compound qualification.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Compound data structures


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-23. Compound data structures AS068.1

Notes:
A data structure can contain another data structure as shown in this example. Notice the qualified
naming in the example. Look particularly at:
DS2.SubFld3.SubFld1 = Hello';'
Because Subfld1 is a subfield of SubFld2, a data structure that is defined like DS1, we reference
the subfield of the DS2 data structure in this fashion.

7-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

LikeRec keyword
IBM i

z %Kds(data-structure-name {:num-keys})

© Copyright IBM Corporation 2002, 2014

Figure 7-24. LikeRec keyword AS068.1

Notes:
This feature enables you to describe a DS based on a record format. Any record format that is used
in this way must be declared on an F-spec in your program.
Notice several things in this example:
1. We are using a DS to extract a key for the POLine_Fmt record format. Note the *Key
parameter. This parameter extracts only those fields that make up the record key in the order
that they are defined in the K specs of the file's DDS. There are several other options:
- *All: All fields in the external record are extracted.
- *Input: All input-capable fields are extracted. This is the default.
- *Output: All output-capable fields are extracted.
2. When processing the record using the %KDS BiF, you can reference the DS where the key is
defined. %Kds is allowed as the search argument for any keyed Input/Output operation (Chain,
Delete, ReadE, ReadPe, SetGt, SetLL) coded in a free-form group.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Arrays within data structure


IBM i

ItemNo Desc QtyOH QtyOO Sold

20001 |Telephone, one line | 10 | 6 | 100|


20002 |Telephone, two line | 5 | 12 | 560|
20003 |Speaker Telephone | 6 | 8 | 25|
20004 |Telephone Extension Cord | 25 | 10 | 56|
20005 |Dry Erase Marker Packs | 428 | 10 | 1200|
20006 |Executive Chairs | 10 | 2 | 15|
20007 |Secretarial Chairs | 13 | 5 | 156|
20008 |Desk Calendar Pads | 56 | 10 | 1543|
20009 |Diskette Mailers | 128 | 200 | 234|

© Copyright IBM Corporation 2002, 2014

Figure 7-25. Arrays within data structure AS068.1

Notes:
We discussed arrays earlier. An array is defined as a group of fields of the same data type.
A data structure is a grouping of fields that can be a combination of one or more data types. A
data structure could be compared to a record.
An Array Data Structure is a data structure that is defined with keyword Dim.
This visual shows a group of records that we describe as an array within a data structure.

7-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Array data structure


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-26. Array data structure AS068.1

Notes:
Notice that the Dim keyword applies to the whole data structure. Also, notice the Qualified
keyword. Each record of the SlsHst file is read, which gives us the Sales and Profit fields in
addition to the Region that made the sale and profit.
By using the Region as the index to the arrays, and using qualified naming, we calculate the total
sales and profit for each region that is read from the SlsHst file.
Notice also the use of the abbreviated assignment operator +=. In this situation, this form saves you
having to code the qualified name of the array element twice.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Array as a component of a data structure


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-27. Array as a component of a data structure AS068.1

Notes:
Suppose that we had an application where we had an array that we wanted to divide into subfields.
How could we do this? We know that the Overlay keyword can be used in a data structure to
subdivide a field into subfields. We can also make an array part of a data structure and because of
that subdivide elements of the array into subfields using Overlay.
The visual is a variation of the previous example. The DIM keyword is placed against the Totals
subfield within the data structure. Two further subfields overlay Totals, allowing the SortA operation
to be used with either TotSales or TotProfit. The association between TotSales and TotProfit is
maintained.

7-32 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Multidimensional array
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-28. Multidimensional array AS068.1

Notes:
Earlier we discussed how to build a single dimensional array. This example expands that capability,
using an array data structure to create a multidimensional array.
Elements can be summed across an array, or summed across a D/S. We have built a 2-dimensional
array.
In this case, the array Sales has 12 elements, each containing Sales values for each month. The
array DS allows us to track Sales by Region. Thus, Sales can be summed for the year by region.
A qualified data structure is used with the DIM keyword.
Notice the way that we qualify the argument for the %Xfoot BiF. We are interested in totals by
region and thus want to work with the instance of the SalesByRegion DS based on the value of
Reg as we loop in the For.
For array data structures, all occurrences are initialized based upon the data type. You should
always use the Inz keyword to initialize a data structure and override at the subfield level as
required.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Reinitializing data structures


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-29. Reinitializing data structures AS068.1

Notes:
Clear and Reset have many uses but here we show you an example of how Reset can now be
used to reinitialize a data structure, in this case, an array DS.
The Clear sets elements in a structure to the appropriate default values of blanks for character data
and zero for numeric data.
Reset sets each element in a structure to the initial value that you specified on the Definition spec
when you initially set up the Data Structure.
Both these opcodes can also be used with other structures, such as record formats. Review the
RPG IV Reference Manual for further information.

7-34 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

What is a data area?


IBM i

JOBA JOBC

PGMA PGMA
Data area

PGMB PGMB

JOBB
PGMC

PGMC

PGMD

© Copyright IBM Corporation 2002, 2014

Figure 7-30. What is a data area? AS068.1

Notes:
A data area is:
• A permanent object of type *DTAARA
• Located in auxiliary storage
• Treated by IBM i as a single ‘field’
One type of data area, the general data area, is created by the user. It is the only data area that
passes data between programs that are run by different operators, as well as between programs
within the same job. A general data area exists until it is explicitly deleted.
A general data area is a storage area external to the program. It is accessible by any authorized
user. It is a permanent i object, which is created and deleted using CL commands, and when
accessed by a program it is treated by IBM i as a single character string or field.
For example:
CRTDTAARA DTAARA(AS07V5LIB/AS07DTAARA) TYPE(*CHAR)
LEN(100) VALUE(‘RPGDataArea')

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Uses for a data area


IBM i

JOBA Next, Order Number JOBC

PGMA xxxxxxx PGMA


Data area

PGMB
PGMB

PGMC JOBB

PGMC
Tax rate
xxxxxxx PGMD
Data area
© Copyright IBM Corporation 2002, 2014

Figure 7-31. Uses for a data area AS068.1

Notes:
A data area is used to store control information that is used by multiple jobs. Because there is only
one field no cursor is required, so opening a data area does not have the overhead that is
associated with opening a database file. As a result, using a data area for control information is
much more efficient than using a control record in a file, as may have been done on other systems.
In this example, the Next Order Number to be processed and the Tax Rate are being stored in
data areas.

7-36 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Comparison of data area types


IBM i

General data area Local data area

Created by User System


Size Variable Fixed
Type *CHAR, *DEC, *LGL *CHAR
Referenced W/I or between jobs W/I job
Number per job Variable One
Deleted by User System

© Copyright IBM Corporation 2002, 2014

Figure 7-32. Comparison of data area types AS068.1

Notes:
This visual compares the two types of data areas that can be use in a local programming
environment. Both the general data area and the local data area (LDA) can be directly accessed by
RPG IV.
The maximum length of a general data area is 2000 characters while the *LDA can be a maximum
of 1024 characters.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Explicitly process a data area


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-33. Explicitly process a data area AS068.1

Notes:
To explicitly process a data area, a combination of the In, Out, or Unlock operations that are
shown on this visual can be used.
You can specify the data area operations (In, Out, and Unlock) for a data area that is explicitly read
in and written out. Before you use a data area data structure with these operations, you would
specify that data area data structure name in the Definition specs.
When a data area is defined in a program, its contents can be retrieved by specifying the In
operation. If *Lock is used an exclusive allow read lock state is imposed on the data area and other
jobs are prevented from accessing it until the program ends, the data area is written to or read
again or an Unlock operation is used to release it.
The data area can be updated, if necessary, by using the Out operation to write its contents back to
disk. The Out operation cannot be used with a data area that has not been locked.
When written with an Out, the data area is unlocked automatically and becomes available for other
jobs, unless the *Lock is specified on the Out. When *Lock is used on the Out operation, the data
area is locked from updates by other jobs, even after it is written by this program.

7-38 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty The Unlock operation can be used to unlock a data area and make it available to other jobs. This
operation does not write contents of the data area back to auxiliary storage. All data areas that are
used in the program are unlocked automatically when the program ends. This is not true of a
subprogram that does not have LR on when its calling program ends. In that case, the data areas
remain locked.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-39
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Naming a data area using a variable


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-34. Naming a data area using a variable AS068.1

Notes:
A data area can be named using a program variable. This variable can be supplied from a display
format or a passed parameter from another program for example.
The variable must be one of the following forms:
‘NAME’
‘LIBRARY/NAME’
‘*LIBL/NAME’
The variable's value must be uppercase or the data area will not be found.
In the example, we show the variable as a program variable initialized in the Definition specs.

7-40 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Implicitly process a data area (1 of 2)


IBM i

RPG implicitly retrieves and


writes data area into the
data structure.

Machine storage
Data area

PROGRAM

Data structure

© Copyright IBM Corporation 2002, 2014

Figure 7-35. Implicitly process a data area (1 of 2) AS068.1

Notes:
As we have seen, a data area can be explicitly read and updated by an RPG IV program using In
and Out. RPG IV can also use what is known as a data area data structure to implicitly retrieve it
during program initialization.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-41
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Implicitly process a data area (2 of 2)


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-36. Implicitly process a data area (2 of 2) AS068.1

Notes:
In this example, the data area Totals might be used to pass information between one program and
another. Totals data area is not being accessed by many programs at once, only by perhaps an
edit or a processing program. This is an important consideration because the data area has a
shared-no-update lock on it while these programs are running because it is defined as a data area
data structure.
The *AUTO in the DTAARA keyword on the line that defines the Totals data structure indicates that
this is a data area data structure. The name of the data area, which must be specified,
corresponds with the name of an existing data area. The *AUTO causes the data area to be
implicitly read (and locked) during program activation, and implicitly written out (and unlocked)
during program termination.

7-42 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Local data area


IBM i

• 1024 bytes of character data

• Created and deleted by IBM i

• *LDA

• Private to your job

• SBMJOB passes to batch job

© Copyright IBM Corporation 2002, 2014

Figure 7-37. Local data area AS068.1

Notes:
A local data area is a special data area that is automatically created and deleted by the system for
each job. The LDA is available, with one exception, only within that job. It is always 1024 bytes of
data that can be processed as a character string and is referenced as *LDA.
The only case in which the contents of an LDA are available to another job is a SBMJOB that is
issued from an interactive job. When the SBMJOB command is run, a snapshot of the status of the
interactive job's LDA is passed to the submitted job and used to set the initial value of its LDA when
the batch job is run.

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-43
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

LDA definition, In and Out


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-38. LDA definition, In and Out AS068.1

Notes:
As shown on this visual, there is an advantage to using a data structure for an LDA, even if updates
are going to be done explicitly. In this case, the data structure that is being used to process the LDA
is named on the Definition specification. Because we referenced a specific subfield of the data
structure, positions in the middle of the LDA can be changed.

7-44 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Checkpoint
IBM i

1. Data structures:
a. Occupy storage
b. Are character strings
c. Can be internally or externally described
d. All of the above

2. True or false: Data areas can be used to communicate


between processes.

3. True or false: Use the %LookUpEQ BiF to find items in an


array.

© Copyright IBM Corporation 2002, 2014

Figure 7-39. Checkpoint AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-45
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Machine exercise: Data structures and data areas


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 7-40. Machine exercise: Data structures and data areas AS068.1

Notes:
Perform the machine exercise Data structures and data areas.

7-46 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Unit summary
IBM i

Having completed this unit, you should be able to:

• Define an array in an RPG IV program

• Use the %LookUpxx and %Xfoot BiFs

• Define a data structure in an RPG IV program

• Name two types of data structures and explain how they would be used

• Define a multidimensional array in an RPG IV program

• Use the Like and LikeDS keywords

• Use Qualified Data Structures

• List one use of a data area

• Define a data area in an RPG IV program

© Copyright IBM Corporation 2002, 2014

Figure 7-41. Unit summary AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 7. Using arrays, data structures, and data areas 7-47
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

7-48 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 8. Accessing the DB2 database using RPG IV

What this unit is about


This unit describes the two types of database files on the i (Power i). It briefly
reviews their creation and discusses how they are accessed in RPG IV
programs. This unit also discusses the format and function of RPG IV file
handling operation codes, including Read, Write, Chain, Update, and Delete.

What you should be able to do


After completing this unit, you should be able to:
• Define physical and logical files in an RPG IV program
• Access data in physical and logical files with the Read and Chain
opcodes
• Modify data in physical and logical files using Write, Update, and Delete
• Use the sequential and random access methods to process data
• Define record keys and use them to process data
• Describe how to embed SQL into an RPG IV program

How you will check your progress


• Checkpoint questions
• Machine exercises
• Given a problem statement, the students code an RPG IV program that
accesses records in the database using I/O operation codes.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:


• Define physical and logical files in an RPG IV program
• Access data in physical and logical files with the Read and
Chain opcodes
• Modify data in physical and logical files using Write, Update,
and Delete
• Use the sequential and random access methods to process
data
• Define record keys and use them to process data
• Describe how to embed SQL into an RPG IV program

© Copyright IBM Corporation 2002, 2014

Figure 8-1. Unit objectives AS068.1

Notes:

8-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

DB file: Physical
IBM i

Physical

Object
header

Format
D
CRTPF
D
S
Access
path

Data
Contains actual data records member
SQL = CREATE TABLE

© Copyright IBM Corporation 2002, 2014

Figure 8-2. DB file: Physical AS068.1

Notes:
A physical file is the i object type that holds data records. As a rule, physical files are composed of
four parts:
• Object header
• Format
• Access path
• Member
A physical file stores data records. Using DDS record and field level specifications, you can define
a physical file. At the field level, if one or more fields is designated as the key, you can access
records in the file in either key sequence or arrival sequence. If key fields are not designated, your
access must be in arrival sequence. The access path is what enables record retrieval to use a key.
The access path is the index for the file to all of its data records.
The CREATE TABLE SQL statement does the same job as CRTPF.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

DB file: Logical
IBM i

Physical file
Logical file
6 12 SAM M
7 15 DOT F
2 91 BOB M
10 47 JOY F
1 BETA 4 32 JOE M
2 BOB
3 DON
3 43 DON M
4 JOE 11 21 BEV F
5 PAT
6 SAM D 8 66 DEMI F
D 5 48 PAT M
S
9 99 RAY M
CRTLF 1 01 BETA F

Determines how records are selected and their order when accessed
SQL = CREATE VIEW or CREATE INDEX

© Copyright IBM Corporation 2002, 2014

Figure 8-3. DB file: Logical AS068.1

Notes:
Logical files appear to have data records, but they do not contain data records. Instead, an access
path, or pointers to records in the physical files, are stored in logical files.
A logical file is always based on one or more physical files. The logical file stores an access path
(no data) in its member. It is with logical files on the i that a programmer might define views of data
different from the definition in the physical file.
The traditional relational database operators are available. Record sequencing, record selection,
field projection, record union, and join are all available tools for processing data from a physical file.
• Sequence: Ordering records that are based on one or more fields.
• Selection: Using criteria to include or omit selected records.
• Projection: Choosing which fields are used in a view of the data.
• Union: Taking records from two or more files and presenting them in a view as though they
were coming from one file.
• Join: Picking fields from two or more records from different files and presenting them in a single
record format.

8-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty Although data resides in the physical file, programs can use logical or physical files in order to
manipulate the data.
The CREATE VIEW SQL statement creates a logical file that can be used to do selection, union,
and joins. It allows for more complex presentation of the data than is available through DDS and the
CRTLF command.
The CREATE INDEX SQL statement creates a logical file that can be used by SQL for optimizing
queries.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

DB file descriptions
IBM i

• Define record formats for physical and logical files:


– Single record format for physical files
– One or more record formats for logical files
• Code DDS at levels below (shown highest to lowest):
– Physical file:
• File
• Record
• Field
• Key
– Logical file:
• File
• Record
• Join
• Field
• Key
• Selection
© Copyright IBM Corporation 2002, 2014

Figure 8-4. DB file descriptions AS068.1

Notes:
DB files are defined with Data Definition Specifications (DDS). Keywords enhance your file
definitions and can be entered at four levels for physical files and six levels for logical files.
Physical files have one record format.
Logical files have one or more record formats.
The file, record, and field levels for keywords work for database files just as they do for printer files.
But you can define key fields for both physical and logical files. Also, you can specify record
selection criteria for logical files. You can define a logical file to join fields together from different
physical files to present to a program as though they were in a single record.
There are two types of logical files. A non-join logical file provides a one-to-one relationship with the
physical files on which it is based. Some advantages to using a non-join logical file in an RPG
program:
• Alternate sequence (from physical file) of data records
• Program that is not burdened with record selection
• Efficiency; only necessary fields are part of record buffers

8-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty A join logical file allows data from more than one physical file to be presented in a single record
format. Along with the other advantages, join logical files provide your RPG IV programs with the
ability to access data from up to 32 different files by doing only ONE read. The alternative would be
to read records from multiple physical files for the data. There are a few things to remember about
join logical files:
• Join logical files cannot be updated. They are read only.
• One or more common fields must exist in the physical files that are being joined.
• The maximum number of physical files that can be joined is thirty-two.

Note

Files can also be defined with SQL CREATE statements. The tables, views, and indexes that are
created can be accessed as files in RPG IV programs. There are things that you can do in an SQL
VIEW that cannot be done with DDS. It is recommended to look at using SQL Data Definition
Language (DDL) to create tables (physical files) and views (logical files) instead of using DDS.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

DDS limits
IBM i

Description DDS

Record length 32,766


Number of fields 8,000
Character field 32,766
Numeric field 63 Digits
Decimal positions 63 Digits
Key fields (composite) 120
Key length 32,768
File members 32,767

© Copyright IBM Corporation 2002, 2014

Figure 8-5. DDS limits AS068.1

Notes:
These limits coincide with most of the limits of RPG IV.

8-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Physical file DDS keywords


IBM i

ALTSEQ COLHDG
CCSID DFT
FCFO REFFLD
FIFO VALUES
LIFO VARLEN
REF ABSVAL
UNIQUE DESCEND
TEXT ZONE
CHECK

blank - Field level - Key level


- Record level
- File level

© Copyright IBM Corporation 2002, 2014

Figure 8-6. Physical file DDS keywords AS068.1

Notes:
Refer to the DDS section of the IBM i IBM Knowledge Center for complete listings and details.
Reference:
DDS Reference: Physical and Logical Files, Keywords for Physical and Logical Files

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Logical file DDS keywords


IBM i

ALTSEQ JFLD VARLEN


DYNSLT JOIN ABSVAL
FCFO CMP DESCEND
FIFO COLHDG ZONE
JDFTVAL CONCAT ALL
LIFO JREF CMP
REFACCPTH RENAME RANGE
UNIQUE SST VALUES
JFILE TEXT
PFILE VALUES

blank - Field level - Key level


- Record level - Join level
- File level - Select/Omit level
© Copyright IBM Corporation 2002, 2014

Figure 8-7. Logical file DDS keywords AS068.1

Notes:
Refer to the DDS section of the IBM Knowledge Center for complete listings and details.
Reference:
DDS Reference: Physical and Logical Files, Keywords for Physical and Logical Files

8-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

DDS field reference file


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-8. DDS field reference file AS068.1

Notes:
This is a subset of the DDS from the course exercises. All fields for the application are defined in
the data dictionary, named DICTIONARY, the field reference file. The physical file, VENDOR_PF,
defines a file that references these definitions. The fields are referenced in the sample Physical file
and the Logical file on the next visual.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

DDS: PF/LF
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-9. DDS: PF/LF AS068.1

Notes:
The physical file, VENDOR_PF, references the field definitions in the field reference file,
DICTIONARY.
The logical file, VNDNAM_LF, in the visual is simply a different ordering of the physical file. This uses
the vendor name as the access path.
REFFLD, a field-level keyword, is used in the PF DDS when:
• You are basing field definition on fields from more than one file.
• The field name that you are defining is based on a field in another file but differs in aspects such
as length.
A key is composite when more than one field is used to define the key.

8-12 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Creating DB files
IBM i

Enter DDS
using LPEX
Syntax
checking

DDS
source
file
Listing
of source Member X
Compile
database file
Physical
file X Member Y
Descriptions (compile DDS Source)
Data and errors

Logical User steps


file Y
Data path
Access path

© Copyright IBM Corporation 2002, 2014

Figure 8-10. Creating DB files AS068.1

Notes:
DDS source members for database files are specified as PF or LF for physical and logical files. The
PF and LF prompts in LPEX provide the correct formats when keying the source statements.
CRTPF and CRTLF are the CL commands that create the database file objects. There are many
parameters that correspond to various physical and logical file attributes. Use the attributes
appropriate to your needs.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Helpful commands
IBM i

CMD function

DSPFD File definitions


DSPFFD Field definitions
DSPPFM Records in PF
DSPDBR File relationships
DSPPGMREF Objects used by program
CPYF Copies data records

© Copyright IBM Corporation 2002, 2014

Figure 8-11. Helpful commands AS068.1

Notes:
The commands on this visual are helpful when you are exploring file definitions, relationships,
content, and use.
• DSPFD provides information that is retrieved from file descriptions for a database file.
• DSPFFD provides field-level information for one or more files.
• DSPPFM displays the contents of a physical file's member.
• DSPDBR provides relational information about database files. It identifies the logical files
dependent on a specific file, files that use a specific record format, or the file members that
depend on a specific file member.
• DSPPGMREF provides a list of the system objects that are referred to by the specified programs.
For RPG, *FILE, *DTAARA and *PGM are the system objects that are provided by this
command.
• CPYF copies all or part of a file from the database or from an external device to the database or
to an external device.

8-14 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty RDi has several ways of displaying much of this same information in a GUI environment. It also has
string search capabilities better than what can be done using some of the legacy functions on the
system.
Another useful tool for examining data is the SQL SELECT statement. You can also examine the
contents and characteristics of a file with System i Navigator.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

File operations
IBM i
• Input files:
– Sequential:
• Read
• SetLL / Setgt
• ReadE / ReadP / ReadPE
– Random
• Chain
• Output files:
• Write
• Update files:
– All opcodes shown here
– Plus:
• Delete
• Update
• Build composite keys with:
– KList/KFld (V5R1 or earlier)
– Pass key components as parameters (V5R2 or later)

© Copyright IBM Corporation 2002, 2014

Figure 8-12. File operations AS068.1

Notes:
There are many choices that must be made concerning file access and record manipulation when
processing database files with RPG IV programs:
• What must your program do to the files and records in question?
• Are you adding new records to the file?
• Are you updating records currently in the file?
• Are you simply reading records for input or perhaps to print a report?
How you want to process a file determines how you declare it on the File spec and what operation
codes are used to read and change the data.
File type, position 17 of the file specification or the usage keyword, designates how the file is used
by the program.
• Usage(*input) (I)nput files contain data records that are to be read by the program.
• Usage(*output) (O)utput files are designed for the program to write (new) records to the file.

8-16 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty • Usage(*update : *delete : *output)(U)pdate files can be used as input, can have records
added, and can additionally have records that are deleted and changed.
Sequential processing of records is used primarily for batch processing. Reading typically starts
with the first record in the file. With each subsequent read operation, the next record in the file is
read until the program reaches end of file.
Random processing allows direct retrieval of a specific record that is based on the value of a key
field or Relative Record Number (RRN). This allows your program to directly select a specific record
for processing without having to process all the records before the one you want sequentially.
RPG IV offers several operation codes for accessing data from full procedural database files. Some
of these operations are valid for sequential processing while others are used for random access
processing.
Sequential access means that records are retrieved in either key order if the file has a key that is
designated, or in arrival (first-in-first-out) sequence for non-keyed files.
Random access allows specific record retrieval that is based on the value of a key field or relative
record number. This kind of access enables the retrieval of the record you want, without any
sequential processing.
We use KList and KFld to describe a composite key in your RPG IV programs that are written at
V5R1 or earlier. In V5R2, you can build a composite key in a parameter list that is the argument for
the appropriate opcodes. We learn more later in this unit.
To use the Write operation with a file declared for update, you must also declare that you want to
add records to the file with an ‘A’ in column 20 or the USAGE(*output) keyword.
References:
ILE RPG Language Reference, Operation Codes

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

File-related BiFs and extenders


IBM i

• BiFs
– %Found(FileName) Record found?
– %Open(FileName) Files open?
– %Eof(FileName) EOF (or BOF) reached?
– %Equal(FileName) Key match to search argument?
– %Error previous I/O failed?
– %Kds Concatenated key data structure
• BiFs reference file name NOT record format!
• Operation extenders

– E is required with %Error

© Copyright IBM Corporation 2002, 2014

Figure 8-13. File-related BiFs and extenders AS068.1

Notes:
Recent releases of RPG IV are enhanced so that in almost all cases, it is unnecessary to use
indicators to determine the answer to the typical questions that a program would ask following an
I/O operation:
• %Found(FileName)
For a random read (Chain), a delete (DELETE) or cursor positioning operation, was a record
found that satisfied the search condition defined by a key. %Found returns a '1' if search is
successful and '0' if it is unsuccessful.
The FileName is expected as a parameter.
• %Open(FileName)
Is the FileName specified open? %Open returns a '1' if the file is open and a '0' if it is closed.
• %Eof(FileName)
This BiF checks whether the file specified is at end of file for read (Read, ReadE, ReadP,
ReadPE, and ReadC) and write (Write) operations. For read operations that process records

8-18 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty backwards %Eof checks for beginning of file (BOF). %Eof returns a '1' if either EOF or BOF is
reached for the applicable operation. Otherwise, it is set to '0'.
• %Equal(FileName)
The %Equal BiF is used to check whether the previously executed cursor positioning operation
for the specified filename resulted in an equal match to the search key.
• %Error
The %Error BiF can be used to determine whether the previously executed operation ended
with an error. This BiF replaces the error indicator that can be used with I/O opcodes. It is used
with the E opcode extender.
• %Kds
The %Kds BiF enables the construction of a composite key with a data structure.
File BiFs always reference the filename even if the I/O opcode references a record format.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

File open and close: Explicit or implicit?


IBM i

IMPLICIT versus EXPLICIT

RPG versus PROGRAMMER

Explicit (perhaps) when:


• Using file once
• Many files; reduce program initialization
• Inquiry program to access one of many files

© Copyright IBM Corporation 2002, 2014

Figure 8-14. File open and close: Explicit or implicit? AS068.1

Notes:
RPG IV, by default, automatically opens all files at program initiation. A programmer can choose to
override this automatic process and elect to EXPLICITLY open or close a file within the program.
An accepted programming practice is to not keep a file open any longer than it needs to have
access to the data from the file. If you need access to a file for a brief period of the program's total
runtime, the program should control that file's opening and closing. The visual presents the
following reasons for choosing explicit opens and closes:
• Using a file once
• Many files: Reduce number that is opened at program start
• Inquiry program accesses one of many files

8-20 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Explicit open and close


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-15. Explicit open and close AS068.1

Notes:
RPG IV has two operations (Open and Close) that allow the explicit control of file opens and
closes. You can explicitly close a file that RPG IV implicitly opens. If you want to control the first
open of a file in a program, the keyword USROPN must be specified in the File specification for the
appropriate file. Once a file is opened, either explicitly by the program or implicitly by program
initialization and then closed using the Close opcode, the Open operation can follow in execution
sequence.
This example shows FileX designated for explicit opening by the program. The Open operation
opens the file and the close operation closes it. The only required entry for both operations is the file
name after the opcode.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Open data path


IBM i

FILEX

© Copyright IBM Corporation 2002, 2014

Figure 8-16. Open data path AS068.1

Notes:
An open data path (ODP) is an I/O area that is opened for every file that you process in your
program.
You can think of the ODP as the bridge built between your program and data files it is accessing.
The ODP contains the record buffer and the file cursor. In this topic, we discuss RPG IV operation
codes that allow the positioning of the file cursor from within your program.
Using the SHARE(*YES) parameter (CRTPF/CRTLF or CHGPF/CHGLF) lets two or more programs
running in the same job or activation group share an open data path (ODP). An open data path is
the path through which all input/output operations for the file are performed. In a sense, it connects
the program to a file. If you do not specify the SHARE(*YES) parameter for a file, a new open data
path is created every time that file is opened.
If an active file is opened more than once by the same program in the same job or activation group,
you can use the active ODP for the file with the current open of the file if the program terminated
with *InLR off on the prior call.

8-22 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Data can be accessed


IBM i

• Externally described file:


– By file name
– By record format name
• Program-described file
– By file name only

© Copyright IBM Corporation 2002, 2014

Figure 8-17. Data can be accessed AS068.1

Notes:
When using operation codes that manipulate data records, notice the name of the file on which the
operation acts. In some instances (often in legacy programs), you reference the name of a record
format of a file instead of the file name. For example, you would want to reference a specific record
format name when a data file has more than one record format (a logical database file allows more
than one record format), and you would like to access a particular type of record.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Sequential processing: Read


IBM i

95670 Read FileX


Read Format1
80321
37910
37910
37910
33820
20358
20358
20358
20358
05210
01315
01315
01315
00035

FILEX (FORMAT1)

© Copyright IBM Corporation 2002, 2014

Figure 8-18. Sequential processing: Read AS068.1

Notes:
Sequential reads can be done using either the file name or record format name. It is recommended
that you be consistent in the one you use.

8-24 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Sequential processing: Read example


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-19. Sequential processing: Read example AS068.1

Notes:
The Read operation retrieves records sequentially. A file name or a record format name designates
which file or record format in the file to access. The %Eof should be used to check when end of file
is reached.
To use a record format name, the file must be externally described.
Read under format results in only those records with this particular format presented to the
program.
Reading records with the file name results in all records, whatever their format, being presented to
the program.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Sequential processing: Record addition with Write


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-20. Sequential processing: Record addition with Write AS068.1

Notes:
The *output is required in the usage keyword of the file's File spec, when the file is opened for
output.
In the first example, records are added to an existing file. In the second example, we are writing to
a new file.
Written records are always put at the end of the existing file unless the file specifies to reuse
deleted records. The system takes care of placing new records into the file so the developer does
not have to be concerned about it.
While it is allowed to write by relative record number, it is not a recommended practice and we will
not demonstrate how to do it.

8-26 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Position file cursor with SetLL


IBM i

95670 Read FileX


SetLL Key FileX;
where Key = 20000 Read Format1
80321
Positions the file cursor37910
37910
37910
33820
20358
20358
20358
20358
05210
01315
01315
01315
00035

FILEX (FORMAT1)

© Copyright IBM Corporation 2002, 2014

Figure 8-21. Position file cursor with SetLL AS068.1

Notes:
The SetLL (set lower limit) operation is used to position the file cursor to point to a specific record in
the file. The cursor is positioned at the next record that has a key or relative record number that is
greater than or equal to the search argument (key or relative record number) specified to the
immediate right of the SetLL.
This operation code provides flexibility in where to start sequentially reading a file, especially when
you want to begin processing of a record other than the first one in the file. It can also be used to
reposition the file at the beginning once end of file is reached.
SetLL automatically checks for the existence of a record with the key used as an argument. In the
example, record key 20000 does not exist, and therefore, the file cursor is placed at the next higher
record key, 20358.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Position file cursor with SetLL: Example


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-22. Position file cursor with SetLL: Example AS068.1

Notes:
Built-in functions work together with SetLL to provide information that helps you to continue
processing. Remember SetLL positions the file cursor at the record that is equal to or greater than
the search key or RRN:
%found = '1'
Cursor that is positioned at first record greater than the key or RRN.
%equal = '1'
Cursor that is positioned at record equal to the key or RRN.
%error = '1'
Error occurred; must use with E extender.
Also, figurative constants can be used to position the file.
The notes and examples of using figurative constants that follow assume *LOVAL and *HIVAL are
not used as actual keys in the file.

8-28 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty When used with a file with a composite key, figurative constants are treated as though each field of
the key contained the figurative constant value. Using SETLL with *LOVAL positions the file so that
the first read retrieves the record with the lowest key. In most cases, when duplicate keys are not
allowed, *HIVAL positions the file so that a ReadP retrieves the last record in the file or a Read
receives an end-of-file.
Note *LOVAL cannot be used to position the file cursor for a file to be processed by RRN. *LOVAL
generates an invalid RRN of -999999...9. To position the cursor at the beginning of a file to be
processed by RRN, you would use:
SetLL 1 FileX;
*START and *END are alternate ways to position the file cursor and are better ways to position to
the beginning and end of file than *LOVAL/1 and *HIVAL.
SetLL does not perform an implicit Read or Write. It positions the file cursor, it does not read
the record.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Random processing: Chain by key


IBM i

Chain Key FileX; 95670


where key = 20358 80321
37910
37910
37910
33820
20358
20358
20358
20358
20358
05210
01315
01315
01315
00035
Chain Key Format1;
FILEX (FORMAT1) where Key = 33820

© Copyright IBM Corporation 2002, 2014

Figure 8-23. Random processing: Chain by key AS068.1

Notes:
RPG IV supports random access of full procedural database files with the Chain operation code. A
Chain to FORMAT1 with a KEY value works the same as a Chain to the file name FileX.

8-30 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Random processing with Chain by record key:
Example
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-24. Random processing with Chain by record key: Example AS068.1

Notes:
The Chain operation requires a record key as the search argument. The literal or data field of the
search argument contains the key value of the record to be randomly read. The argument that
follows the key, also required, contains the name of the file or record format from which the record is
to be randomly retrieved. You can use the %found BiF to check whether or not a record was found
on the Chain.
In the example, the field, KEY, contains a value of the key argument to the record in FILEX that you
want to read. If the Chain does not find a record with that key value, the value of %found is '0'. If
the record is found, the value of %found is '1'. You would code appropriate logic to handle the
found and not found situations. When the file contains records with duplicate keys, such that more
than one record meets the key value criteria, the system retrieves the first record that matches the
key value.
If the Chain is successful, the system positions the file cursor or pointer at the record immediately
following the retrieved record. If a Read is performed following a successful Chain, the record
immediately after the Chained record, is read. Conversely, if the Chain is unsuccessful, a sequential
read operation cannot follow it without a cursor positioning operation such as another Chain, SetLL,
or SetGT (which is covered soon).

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Random processing composite key (1 of 2)


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-25. Random processing composite key (1 of 2) AS068.1

Notes:
V5R1 and earlier releases only!
Use the KList and KFld operations to define a key field search argument when an externally
described file has a key made up of two or more fields. When defined to your program, the
composite key can be used as Factor 1 for operations such as Chain, SetLL, ReadE.
KList names the field your program uses to represent your composite key. In the DDS, the
composite key contains three fields, but it could also contain a partial key that is only composed of
just FLDA and FLDB or simply FLDA only.
KFld specifies a field that participates in the concatenation of the three fields that make up the
composite key.
KList and KFlds can be located anywhere in your calculations. Notice that the subfields of the
composite key are defined in D-specs. The resulting composite key is the argument that is used as
a key to the file, FileX.

8-32 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Random processing composite key (2 of 2)


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-26. Random processing composite key (2 of 2) AS068.1

Notes:
V5R2 and later releases!
Although the KList/KFld method is supported, there are better methods that you can code to build a
composite key. The key can be passed as a string of parameters. The order of the parameters
determines the hierarchy of the constructed key.
Alternatively, you can use the %Kds BiF. This allows the construction of a composite key as a data
structure. The data structure can be externally defined, as shown in the example.
These two methods are available for any opcode that can use a key: Chain, Delete, ReadE
ReadPE, SetLL, and SetGT.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Random processing with Chain by Rrn: Example


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-27. Random processing with Chain by RRN: Example AS068.1

Notes:
When you leave the record address type (RAT) (position 34 of a fixed format File spec) blank or
don’t specify the ‘keyed’ keyword for a file, all Chain operations must be processed based on a
relative record number.
Rrn is a field whose value is used to retrieve the record corresponding to that relative position in the
file. If Rrn equals 6, the sixth record in the file is retrieved.
Rrn could be defined in Definition specs as shown in the example, or it could be read from a data
file.

8-34 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Sequential processing: ReadP


IBM i

SetLL *End FileX ReadP FileX


ReadP Format1 95670
80321
37910
37910
37910
33820
20358
20358
20358
20358
20358
05210
01315
01315
01315
00035
FILEX (FORMAT1)

© Copyright IBM Corporation 2002, 2014

Figure 8-28. Sequential processing: ReadP AS068.1

Notes:
The ReadP (read prior record) operation, like the Read operation, sequentially reads the file. The
difference between the two operations is the direction of the read. ReadP moves backwards
(toward the front) through the file. You use the %eof BiF to handle reaching the beginning of file
(BOF).
Just as Read gets the next sequential record from the file, ReadP retrieves the prior record from
point of cursor. This operation reads the file sequentially backwards.
SetLL with *HIVAL or *END is a good method for positioning to EOF in order for ReadP to read
backwards or simply to read only the last record.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-35
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Sequential processing: ReadE


IBM i

SetLL Key FileX ReadE 20358 FileX


95670 ReadE 20358 Format1
where Key = 20358
80321
Positions the file cursor
37910
37910
37910
33820
20358
20358
20358
20358
20358
05210
01315
01315
01315
00035
FILEX (FORMAT1)

© Copyright IBM Corporation 2002, 2014

Figure 8-29. Sequential processing: ReadE AS068.1

Notes:
Use the ReadE (read equal) operation code to sequentially read the next record of a file if the key of
that record matches the value that is specified by the first argument.
This operation code can help process a group of records with identical keys.

8-36 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Sequential processing: ReadE example


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-30. Sequential processing: ReadE example AS068.1

Notes:
This example starts with a Chain to FileX. If a record is found (the Chain is successful), the %Found
BiF is set to '1' and the code within the DoU loop is processed. At the end of the loop, we request a
read of the next record with the same KEY as the initial Chained record. This is a common method
for processing sets of records with duplicate keys in a file.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-37
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Positioning file cursor: SetGT


IBM i

SetGT Key FileX 95670 Read Format1


where Key = 20000 80321
Positions the file cursor 37910
37910
37910
33820
20358
20358
20358
20358
20358
05210
01315
01315
01315
00035

FILEX (FORMAT1)

© Copyright IBM Corporation 2002, 2014

Figure 8-31. Positioning file cursor: SetGT AS068.1

Notes:
Use the SetGT (Set greater than) operation to position the cursor (pointer) in the file. The cursor is
positioned at the next record that is greater than the key or relative record number that is specified
as the search argument.

8-38 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

ReadP and SetGT


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-32. ReadP and SetGT AS068.1

Notes:
This example uses SetGT and the search field KEY to position the file cursor to the first record
whose value is greater than the value of the search field KEY in FILEX. Once the cursor is
positioned, ReadP is used to read previous (or backwards) in the file.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-39
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

ReadPE
IBM i

95670 ReadPE 20358 FileX


SetGT Key FileX
ReadPE 20358 Format1
where Key = 20358 80321
Positions the file cursor 37910
37910
37910
33820
20358
20358
20358
20358
20358
05210
01315
01315
01315
00035
FILEX (FORMAT1)

© Copyright IBM Corporation 2002, 2014

Figure 8-33. ReadPE AS068.1

Notes:
Use the ReadPE (read prior equal) operation code to sequentially read the previous record of a file
if the key of that record matches the value that is specified by the key search argument. This
operation code can help process a group of records with identical keys in a backward (toward the
front) fashion.

8-40 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Update
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-34. Update AS068.1

Notes:
File maintenance involves adding or deleting records from database files or changing the
information in database records. You designate a file as update-capable by coding a U in position
17 of the File spec for fixed format or coding *update as a parameter on the usage keyword for free
format.
The update operation rewrites a single record, replacing all of the fields for the record to be updated
to the file specified. You must have a valid record format name of the file to be updated if the file is
externally described. Before you can update a record, the record must be retrieved by successfully
completing a Read or a Chain operation in order to establish which record is to be updated.
You can use the %Fields BiF to identify the specific fields to be updated. Refer to the Reference
manual for further details.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-41
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Database record locks


IBM i

• Program can lock only one record per file:


– A record is locked when a program reads it from an update file.
– A record is released when the program:
• Updates the locked record of the update file
• Explicitly unlocks the record with the UNLOCK opcode
• Closes the update file
• Reads another record in the same file for update

© Copyright IBM Corporation 2002, 2014

Figure 8-35. Database record locks AS068.1

Notes:
On any multi-user system, problems can arise with the simultaneous use of the same database file.
It is possible that if two users access the same record for update, change the record, and then
rewrite it to the file, one of the user's changes might get lost. File locking and record locking are two
approaches that help programmers deal with this kind of problem.
File locking is the easiest lock to implement although it is not recommended unless required by the
circumstances of the application. By using CL commands, you can limit access to a file to one user
at a time.
From a user's viewpoint, it is more practical to enable multiple user access to the same files at the
same time. RPG IV has a built-in, automatic locking feature that keeps users from updating the
same record. A record is locked when it is read for update, and released when the record is
updated, another record is read from the file, or the file is closed.

8-42 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Record locking
IBM i

PROGA

FILEX

BOB

Other programs can process other data but the


record BOB is locked by PROGA.
© Copyright IBM Corporation 2002, 2014

Figure 8-36. Record locking AS068.1

Notes:
A record lock is placed on a record as soon as a read is performed to an update-capable file. In this
visual, each record is read in a loop. Each record (for example, for employee Bob) is locked until
the next Read, or an Update is performed.
This can cause a problem for another program trying to access the same record. The other program
might abend because it was waiting too long to read the record or because of some other
exception. The programmer might need to manage record locking when the job might become
disconnected or stuck in a wait.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-43
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Read update file without locking record


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-37. Read update file without locking record AS068.1

Notes:
The operation extender N allows a record to be read from an update file and not locked.
Note that we have used the special value *KEY for ReadE and ReadPE. This allows the next record
to be retrieved with the same key-value as the current record.

8-44 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Releasing a locked record


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-38. Releasing a locked record AS068.1

Notes:
If no changes to a locked record are required, you can release it from its locked state with the
Unlock operation.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-45
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Considerations when releasing locked record


IBM i

• Has record changed since read?


• If so, how do you detect record change?
• Use timestamps, flags, and record image comparison.

© Copyright IBM Corporation 2002, 2014

Figure 8-39. Considerations when releasing locked record AS068.1

Notes:

8-46 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Delete
IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-40. Delete AS068.1

Notes:
If a key or relative record number value is specified on a Delete operation, you must use a BiF to
check the result.
Use %Found to test that the record you want to delete was found. This is the more common form of
delete.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-47
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Deleted records
IBM i

39100
38402
38300
38226
25415
25410
25400
25328
19418
19415
19300
19212
18270
13460
13458
13457

FILE Y (FORMAT2)

© Copyright IBM Corporation 2002, 2014

Figure 8-41. Deleted records AS068.1

Notes:
You must take a specific action to remove deleted records from a file. Some of your choices are:
• The CL command RGZPFM can be used to compress (remove deleted records) and optionally
reorganize (order) the data records of a file member.
• You can use CPYF to remove deleted records from a file by copying the file to a new location.
• An alternate solution is to have the system automatically reuse deleted record space for new
records by specifying REUSEDLT(*YES) on a create or change physical file command. Reuse
deleted records *YES is the default when creating an SQL table.

8-48 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

INFDS: File information data structure


IBM i

z *File = first 8 characters of filename


z Retrieve full filename from pos 83-92 of InfDS
© Copyright IBM Corporation 2002, 2014

Figure 8-42. INFDS: File information data structure AS068.1

Notes:
The file information data structure (known as the INFDS) contains useful data for exception
handling in a specific format that you can use in your RPG IV programs.
This data is described in a data structure. Certain subfields are redefined using special RPG IV
names beginning with an asterisk (*).
The INFDS provides information to your program about the file and I/O operations to the file. A file
information data structure can be uniquely linked to each file used by your program.
This file information data structure example provides us with the field Error, and many other fields,
that can be used to fetch the error status code for the file.
There is also the %Status BiF that retrieves the value of the error status code (like the *STATUS
field of the INFDS) for the file. %Status(filename) is set regardless of whether you have coded the
INFDS in your program.
The relationship between EmpMast and a file informational data structure, EmpMastDS is made
on the File specification. The requested information is defined in the definition specifications where
program subfields are assigned values from the system's file, open and I/O feedback areas. These
values are assigned by using the system keywords or overlays to the positions.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-49
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

The RPG IV Reference Manual is helpful in locating some of the more commonly used subfields as
well as detailing from/to positions, data format, field length, and keyword, if any.
The layout of the data in the INFDS includes:
• A standard layout area that applies to all file types:
- File Feedback (length is 80)
- Open Feedback (length is 160)
- Input/Output Feedback (length is 126)
• A variable layout portion depending on file type:
- Device Specific Feedback
- Get Attributes Feedback
Some areas of the INFDS are updated for every I/O operation. You can use the opcode, Post, to
refresh the File Information Data Structure.

Note

The *FILE keyword retrieves only the first eight characters of the file name. It is much better to
retrieve the full file name from positions 83-92 of the INFDS.

Finally, think about making the INFDS a copy member of an externally described data structure.
Putting it in a copy member makes one version available to all your developers.

8-50 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Subset of file status codes


IBM i

Code Description

00000 Operation successful


00013 Subfile full
01021 Duplicate key – not allowed
01041 Array/Table sequence error
01211 I/O operation to closed file
01215 Open issued to file already opened
01218 Unable to allocate record
01221 Update without prior Read
01241 Record number not found
01331 Wait time exceeded for Read from WORKSTN file

© Copyright IBM Corporation 2002, 2014

Figure 8-43. Subset of file status codes AS068.1

Notes:
This is a list of some of the commonly used status codes from the file information data structure.
For example, a status of 00000 indicates that the preceding file I/O operation completed normally.
Any file status code with a value of 00100 or greater is considered an exception. If you coded
the E-extender for an opcode with %Error, %Error would be set to ‘1' for a status code of 00100 or
greater that applies.
All values of the file status code can be retrieved using the %Status Built-in Function.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-51
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Handling a duplicate key on write to file


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-44. Handling a duplicate key on write to file AS068.1

Notes:
The E-extender is coded with the Write operation. The %Error BiF is set to ‘1’ whenever the write
does not complete normally, and set to ‘0’ when it is successful. However, the fact that %Error is
set to ‘1’ is not enough to determine that there is a duplicate record in the file.
To be certain of the source of the exception, the program also uses the %Status BiF to test the
value of the file status code.
If the value of %Status is 1021, a duplicate key was found and the program writes the record to a
duplicate key file. In this example, the key must be unique.

8-52 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Note

It might be better still to avoid the duplicate key error altogether. You could use SetLL
(and %Equal) to check the existence of a duplicate key before you attempt the Write. Both methods
workaround the possible error. Doing this not only avoids the error altogether, but it also eliminates
the need for a Read and is more efficient. Which technique you choose depends on the data. If
there is a large proportion of duplicates, then check each record first; if the proportion of duplicates
is small, then rely upon your error handling to deal with them.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-53
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Using SQL in an RPG IV program


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-45. Using SQL in an RPG IV program AS068.1

Notes:
Here is some sample SQL. This is embedded SQL. It starts with an ‘exec sql’ statement. Source
containing SQL has to go through a pre-compiler that turns the SQL statements into tokens that can
be interpreted by the RPG compiler.
The first example is a simple select statement that returns a record. The variables with colons (:) in
front of them are called local variables. These are variables that are defined in your program. The
fields without colons in front are field names in the file that is being queried. The ‘where’ clause
specifies the key to use to find the record. At runtime, the SQL optimizer looks for an access path
(index) that has FIELDA in the first position to use to find a matching record.
Notice that we don’t use the BiFs to see whether we have an error or end of file. The SQL variable
SQLCODE is zero if the select returns a record. It is set to other values if there was a problem with
the select or there are no records that match the query criteria.
The second example is for use when there is more than one record that can match the query. This
would be like doing a chain followed by read equals. Notice that only one field is returned from the
file rather than the whole record.

8-54 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Why use SQL in an RPG IV program?


IBM i

• Automatic input/output blocking


• Ability to update/delete multiple rows in one statement
• Ability to retrieve multiple rows on a fetch
• Can reduce the amount of code in your program by allowing
SQL to do more of the work
Example: We want to read records from a second file that is
based on field values from a first file. Rather than doing a read
from the first file to get the value then doing a SetLL and read
equal from the second, we can do it in one select statement
that returns just the records we want.

© Copyright IBM Corporation 2002, 2014

Figure 8-46. Why use SQL in an RPG IV program? AS068.1

Notes:
Why should you be using SQL instead of the RPG opcodes to process files? Well written SQL can
drastically reduce the amount of code that the program has to have to accomplish the same thing.
SQL is set driven. If you understand how sets can be used to retrieve just the information you want,
you can create an SQL statement to get just the needed data.
It does take a different mindset to code with SQL. You should follow the application developer
training path for SQL to find a class that will teach you more about accessing the IBM i using SQL.

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-55
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Machine exercise: Maintaining database files


IBM i

© Copyright IBM Corporation 2002, 2014

Figure 8-47. Machine exercise: Maintaining database files AS068.1

Notes:
Perform the Maintaining database files exercise.

8-56 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Checkpoint
IBM i

1. True or false: A logical file contains a copy of the data in the


physical file.

2. Database files can be specified (usage keyword on the Dcl-f


specification) as which of the following types?
a. *Input
b. *Output
c. *Combined
d. *Update

3. True or false: SetLL and SetGT are used to position the file
cursor before sequential read operations.

© Copyright IBM Corporation 2002, 2014

Figure 8-48. Checkpoint AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 8. Accessing the DB2 database using RPG IV 8-57
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit summary
IBM i

Having completed this unit, you should be able to:


• Define physical and logical files in an RPG IV program
• Access data in physical and logical files with the Read and
Chain opcodes
• Modify data in physical and logical files using Write, Update,
and Delete
• Use the sequential and random access methods to process
data
• Define record keys and use them to process data
• Describe how to embed SQL into an RPG IV program

© Copyright IBM Corporation 2002, 2014

Figure 8-49. Unit summary AS068.1

Notes:

8-58 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty
Unit 9. What’s next?

What this unit is about


This unit describes the activities that students can perform to apply the
knowledge gained in this class and to prepare to attend the follow-on
courses:
AS07/AS070: RPG IV Programming Intermediate Workshop for IBM i
AS10/AS100: RPG IV Programming Advanced Workshop for IBM i
This is the first in a series of three courses designed to help you to become a
skilled RPG IV programmer. This unit discusses what is taught in these
follow-on courses and why it is important for you to attend.

What you should be able to do


After completing this unit, you should be able to:
• List the prerequisite skills needed prior to attending the Intermediate and
Advanced RPG IV courses
• List the topics of the next course

© Copyright IBM Corp. 2002, 2019 Unit 9. What’s next? 9-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit objectives
IBM i

After completing this unit, you should be able to:


• List the prerequisite skills needed before attending the
advanced RPG IV course
• List the topics in the next course

© Copyright IBM Corporation 2002, 2014

Figure 9-1. Unit objectives AS068.1

Notes:

9-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

What have you learned?


IBM i

• Write simple RPG IV programs to produce reports


• Write simple RPG IV inquiry programs that interact with
displays
• Use the editor to enter and modify source programs and
compile RPG IV programs
• Review compilation listing, and find and correct compilation
errors
• Maintain existing applications written in the RPG IV language
• Use many popular RPG IV built-in functions
• And much more!

© Copyright IBM Corporation 2002, 2014

Figure 9-2. What have you learned? AS068.1

Notes:
You have worked very hard over the past four days. We hope that you think that you have
accomplished a lot by attending this class.
You should now be able to write working RPG IV programs to produce reports and to handle inquiry
displays.
As we said at the beginning of this class, it is the first in a set of two courses that, when followed in
sequence, will provide the skills necessary to be a proficient RPG IV programmer.
You have learned a lot about using the RPG IV language to write applications. To maximize the new
skills that you now have, you must apply this knowledge on the job.

© Copyright IBM Corp. 2002, 2019 Unit 9. What’s next? 9-3


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

To do list
IBM i

• Get hands-on ASAP!


• Read the reference manuals.
• Read articles in trade magazines and on the web.
• Prepare to attend follow-on courses.
• Join your local i users group.
• Participate in www.midrange.com forum lists.

© Copyright IBM Corporation 2002, 2014

Figure 9-3. To do list AS068.1

Notes:

9-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Topics list for next course


IBM i

AS10 - RPG IV Advanced Programming Workshop for IBM i


• Advanced display programs
– Using OVERLAY/OVRDTA/PUTOVR/OVRATR
– Using subfile displays:
• Simple inquiries
• Subfile search
• Other subfile operations
• Subfile record maintenance
• Debugging RPG IV code
• ILE error handling:
– Monitor groups
• Basic API programming
• Advanced RPG IV features (using pointers and user spaces)
• Using C functions
• Using XML

© Copyright IBM Corporation 2002, 2014

Figure 9-4. Topics list for next course AS068.1

Notes:
You should plan to attend the last course in this series next. Some on-the-job experience is strongly
recommended before attending this course.
Knowledge of the features available in Rdi would be helpful as you move forward.

© Copyright IBM Corp. 2002, 2019 Unit 9. What’s next? 9-5


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Useful references and websites


IBM i

• RPG IV reference manuals


• http://www.iprodeveloper.com
• http://www.midrange.com
– http://lists.midrange.com/mailman/listinfo/rpg400-l
– http://lists.midrange.com/mailman/listinfo/wdsci-l
• http://www-03.ibm.com/certify
• http://www.midrangenews.com
• RPG Café
• Modern i zation
• Modernization redbook

© Copyright IBM Corporation 2002, 2014

Figure 9-5. Useful references and websites AS068.1

Notes:
This is a list of some useful documentation as well as some websites that you should explore. Of
particular value are the forum lists, sponsored by www.midrange.com.

9-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V9.0
Student Notebook

Uempty

Unit summary
IBM i

Having completed this unit, you should be able to:


• List the prerequisite skills needed before attending the
advanced RPG IV course
• List the topics in the next course

© Copyright IBM Corporation 2002, 2014

Figure 9-6. Unit summary AS068.1

Notes:

© Copyright IBM Corp. 2002, 2019 Unit 9. What’s next? 9-7


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

9-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP
Appendix A. RPG IV style guide
Reprinted from 'RPG IV Jump Start’ (4th ed) by Bryan Meyers (www.bmeyers.net), with
permission of the author.

Chapter 15
“Rethinking RPG Standards”
Professional programmers appreciate the importance of standards in developing programs that are
readable, understandable, and maintainable. The issue of programming style goes beyond any one
language, but the introduction of the RPG IV syntax demands that you re-examine standards of
RPG style. Now would be a great time to begin thinking about how your own shop’s RPG standards
might change as you move into application development with RPG IV. Make no mistake: Your
existing RPG standards are now obsolete. This chapter presents some issues to think about before
you start feeling your way around RPG IV.

Use comments judiciously


Good programming style can serve a documentary purpose in helping others understand the
source code. If you practice good code-construction techniques, you will find that “less is more”
when it comes to commenting the source. Too many comments are as bad as too few.
Use comments to clarify, not echo, your code. Comments that merely repeat the code add to a
program’s bulk, but not to its value. In general, you should use comments for just three purposes:
• To provide a brief program or procedure summary
• To give a title to a subroutine, procedure, or other section of code
• To explain a technique that is not readily apparent by reading the source

Always include a brief summary at the beginning of a program or procedure. This prologue
should include the following information:
• A program or procedure title
• A brief description of the program’s or procedure’s purpose
• A chronology of changes that includes the date, programmer name, and purpose of each
change
• A summary of indicator usage
• A description of the procedure interface (the return value and parameters)
• An example of how to call the procedure

Use consistent marker line comments to divide major sections of code. For example, you
should definitely section off with lines of dashes (-) or asterisks (*) the declarations, the main
procedure, each subroutine, and any subprocedures. Identify each section for easy reference.
Use blank lines to group related source lines and make them stand out. In general, you
should use completely blank lines instead of blank comment lines to group lines of code, unless

© Copyright IBM Corp. 2002, 2019 Appendix A. RPG IV style guide A-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

you are building a block of comments. Use only one blank line, though; multiple consecutive
blank lines make your program hard to read.
Avoid right-hand end-line comments in columns 81–100. Right-hand comments tend simply
to echo the code, can be lost during program maintenance, and can easily become out of sync
with the line they comment. If a source line is important enough to warrant a comment, it’s
important enough to warrant a comment on a separate line. If the comment merely repeats the
code, eliminate it entirely.

Centralize declarations
With RPG IV, we finally have an area of the program source in which to declare all variables and
constants associated with the program. The D-specs organize all your declarations in one place.
RPG IV still supports the *LIKE DEFINE opcode, along with Z-ADD, Z-SUB, MOVEx, and
CLEAR, to define program variables. But for ease of maintenance as well as program clarity,
you will want to dictate a standard that consolidates all data definition, including work fields, in
D-specs.
Declare all variables within D-specs. Except for key lists and parameter lists, do not declare
variables in C-specs -- not even using *LIKE DEFINE. Define key lists and parameter lists in the
first C-specs of the program, before any executable calculations. Use a prototype definition
instead of an *ENTRY PLIST.
Whenever a literal has a specific meaning, declare it as a named constant in the D-specs.
This practice helps document your code and makes it easier to maintain. One obvious
exception to this rule is the allowable use of 0 and 1 when they make perfect sense in the
context of a statement. For example, if you are going to initialize an accumulator field or
increment a counter, it’s fine to use a hard-coded 0 or 1 in the source.
Indent data item names to improve readability and document data structures. Unlike
many other RPG entries, the name of a defined item need not be left-justified in the D-specs;
take advantage of this feature to help document your code:

A-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++++++++++++++
D ErrMsgDSDS DS
D ErrPrefix 3
D ErrMsgID 4
D ErrMajor 2 OVERLAY(ErrMsgID:1)
D ErrMinor 2 OVERLAY(ErrMsgID:3)

Use length notation instead of positional notation in data structure declarations. D-specs let
you code fields either with specific from and to positions or simply with the length of the field. To
avoid confusion and to better document the field, use length notation consistently. For example,
code:

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8


DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++++++++++++++
D RtnCode DS
D PackedNbr 15P 5

instead of

D RtnCode DS
D PackedNbr 1 8P 5

Use positional notation only when the actual position in a data structure is important. For example,
when coding the program status data structure, the file information data structure, or the return data
structure from an application programming interface (API), you would use positional notation if your
program ignores certain positions leading up to a field or between fields. Using positional notation is
preferable to using unnecessary “filler” variables with length notation:
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++++++++++++++
D APIRtn DS
D PackedNbr 145 152P 5

In this example, to better document the variable, consider overlaying the positionally declared
variable with another variable declared with length notation:

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8


DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++++++++++++++
D APIRtn DS
D Pos145 145 152
D PackNbr 15P 5 OVERLAY(Pos145)

When defining overlapping fields, use the OVERLAY keyword instead of positional notation.
Keyword OVERLAY explicitly ties the declaration of a child variable to that of its parent. Not only

© Copyright IBM Corp. 2002, 2019 Appendix A. RPG IV style guide A-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

does OVERLAY document this relationship, but if the parent moves elsewhere within the
program code, the child follows.
If your program uses compile-time arrays, use the **CTDATA form to identify the
compile-time data. This form effectively documents the identity of the compile-time data, tying
the data at the end of the program to the array declaration in the D-specs. The **CTDATA
syntax also helps you avoid errors by eliminating the need to code compile-time data in the
same order in which you declare multiple arrays.

Expand naming conventions


Perhaps the most important aspect of programming style deals with the names you give to data
items (for example, variables, named constants) and routines. Establish naming conventions that
go beyond the traditional six characters, to fully identify variables and other identifiers. Those extra
characters can make the difference between program code and a program description.
When naming an item, be sure the name fully and accurately describes the item. The
name should be unambiguous, easy to read, and obvious. Although you should exploit RPG
IV’s allowance for long names, do not make your names too long to be useful. Name lengths of
10 to 14 characters are usually sufficient, and longer names may not be practical in many
specifications. When naming a data item, describe the item; when naming a subroutine or
procedure, use a verb/object syntax (similar to a CL command) to describe the process.
Maintain a dictionary of names, verbs, and objects, and use the dictionary to standardize your
naming conventions.
When coding an RPG symbolic name, use mixed case to clarify the named item’s
meaning and use. RPG IV lets you type your source code in upper- and lowercase characters.
Use this feature to clarify named data. For RPG-reserved words and operations, use all
uppercase characters.
Avoid using special characters (for example, @, #, $) when naming items. Although RPG
IV allows an underscore (_) within a name, you can easily avoid using this noise character if you
use mixed case intelligently.

Write indicator-less code


Historically, indicators have been an identifying characteristic of the RPG syntax, but with RPG IV
they are fast becoming relics of an earlier era. Reducing a program’s use of indicators may well be
the single most important thing you can do to improve the program’s readability.
Use indicators as sparingly as possible; go out of your way to eliminate them. At Version
5, RPG completely eliminates the need for conditioning indicators and resulting indicators, and
does not support them in any free-form specifications. At prior release, the only indicators
present in a program should be resulting indicators for opcodes that absolutely require them (for
example, LOOKUP). Whenever possible, use built-in functions (BiFs) instead of indicators.
Remember you can indicate file exception conditions with error-handling BiFs (for
example, %EOF, %ERROR, %FOUND) and an E operation extender to avoid using indicators.
If you must use indicators, name them. V4R2 supports a Boolean data type (N) that serves
the same purpose as an indicator. You can use the INDDS keyword with a display-file

A-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP specification to associate a data structure with the indicators for a display or printer file; you can
then assign meaningful names to the indicators.
Use the EVAL opcode with *Inxx and *ON or *OFF to set the state of indicators. Do not use
the SETON or SETOFF operation, and never use MOVEA to manipulate multiple indicators at
once.
Use indicators only in close proximity to the point where your program sets their
condition. For example, it is bad practice to set an indicator and not test it until several pages
later. If it is not possible to keep the related actions (setting and testing the indicator) together,
move the indicator value to a meaningful variable instead.
Do not use conditioning indicators -- ever. If a program must conditionally execute or avoid a
block of source, explicitly code the condition with a structured comparison opcode, such as IF. If
you are working with old System/36 code, get rid of the blocks of conditioning indicators in the
source. The Version 5 free-form specification does not support conditioning indicators.
Include a description of any indicators you use. It is especially important to document
indicators whose purpose is not obvious by reading the program, such as indicators used to
communicate with display or printer files or the U1–U8 external indicators, if you must use them.

Structured programming techniques


Give those who follow you a fighting chance to understand how your program works by
implementing structured programming techniques at all times. The IF, DOU, DOW, FOR, and
WHEN opcodes are positively elegant. Banish IFxx, DOUxx, DOWxx, and WHxx from your RPG IV
code forever. By the way, you would never use indicators to condition structured opcodes, would
you? Good!
Do not use GOTO, CABxx, or COMP. Instead, substitute a structured alternative, such as
nested IF statements, or status variables to skip code or to direct a program to a specific
location. To compare two values, use the structured opcodes IF and ELSE. To perform loops,
use DOU, DOW, and FOR. Never code your loops by comparing and branching with COMP (or
even IF) and GOTO. Employ ITER to repeat a loop iteration, and use LEAVE for premature exits
from loops, or LEAVESR to prematurely exit subroutines.
Do not use the obsolete IFxx, DOUxx, DOWxx, or WHxx opcodes. The newer forms of
these opcodes (IF, DOU, DOW, and WHEN) support free-format expressions, making those
alternatives more readable. In general, if an opcode offers a free-format alternative, use it. This
rule applies to the DO opcode as well; the free-format FOR operation is usually a better choice,
if you are at V4R4 or later.
Perform multipath comparisons with SELECT/WHEN/OTHER/ENDSL. Deeply nested
IFxx/ELSE/ENDIF code blocks are hard to read and result in an unwieldy accumulation of
ENDIFs at the end of the group. Do not use the obsolete CASxx opcode; instead, use the more
versatile SELECT/WHEN/OTHER/ENDSL construction.
Always qualify END opcodes. Use ENDIF, ENDDO, ENDFOR, ENDSL, or ENDCS as
applicable. This practice can be a great help in deciphering complex blocks of source.
Avoid programming tricks and hidden code. Such maneuvers are not so clever to someone
who does not know the trick. If you think you must add comments to explain how a block of code
works, consider rewriting the code to clarify its purpose. Use of the obscure bit-twiddling

© Copyright IBM Corp. 2002, 2019 Appendix A. RPG IV style guide A-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

opcodes (BITON, BITOFF, MxxZO, TESTB, and TESTZ) may be a sign that your source needs
updating.

Modular programming techniques


The RPG IV syntax, along with the i5 (iSeries)’s Integrated Language Environment (ILE),
encourages a modular approach to application programming. Modularity offers a way to organize
an application, facilitate program maintenance, hide complex logic, and efficiently reuse code
wherever it applies.
Use RPG IV’s prototyping capabilities to define parameters and procedure interfaces.
Prototypes (PR definitions) offer many advantages when you are passing data between
modules and programs. For example, they avoid runtime errors by giving the compiler the ability
to check the data type and number of parameters. Prototypes also let you code literals and
expressions as parameters, declare parameter lists (even the *ENTRY PLIST) in the D-specs,
and pass parameters by value and by read-only reference, as well as by reference.
Store prototypes in /COPY members. For each module, code a /COPY member containing
the procedure prototype for each exported procedure in that module. Then include a reference
to that /COPY module in each module that refers to the procedures in the called module. This
practice saves you from typing the prototypes each time you need them and reduces errors.
Include constant declarations for a module in the same /COPY member as the prototypes
for that module. If you then reference the /COPY member in any module that refers to the
called module, you have effectively globalized the declaration of those constants.
Use IMPORT and EXPORT only for global data items. The IMPORT and EXPORT keywords
let you share data among the procedures in a program without explicitly passing the data as
parameters -- in other words, they provide a hidden interface between procedures. Limit use of
these keywords to data items that are truly global in the program -- usually values that are set
once and then never changed.
Hone Your Modular Programming Skills
Creating effective modular programs requires two things: an architecture that offers
high-performance calls with a uniform runtime model for high-level languages, and a language (or
languages) capable of harnessing that architecture. With ILE, the i (System i) has the necessary
program/procedure call environment, and with RPG IV, the RPG programmer has a language that
can exploit that environment. RPG’s support for subprocedures (covered in Chapter 14) is an
especially welcome tool as you work on modularizing applications and creating repositories of
reusable code.
As you write new ILE applications, you will probably find yourself using program and/or
procedure calls far more often than in the past. Consider a date conversion routine required by
six fields in a one-million-record file. If you were to add that routine to an RPG/400 program as
an external call, the six million times the routine is called could significantly degrade
performance.
In the past, your only real option for this scenario was to code the routine as an internal
subroutine. With ILE’s static call mechanisms, though, you can code it as a subprocedure or a
called program, with the effective performance of a subroutine call. This means you can rethink

A-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP the structure of all your monolithic, inline RPG programs and achieve a substantial level of
modularity without a trade-off in speed.
As you increasingly exploit the benefits of modular procedure calls, you need to know how best
to carve up your code. Robust modular programming is not achieved by butchering old code
into random chunks; rather, it requires filleting code into planned, manageable, reusable pieces.
You need to engineer each module so that it does one thing well and so that your call interfaces
are simple, yet flexible enough to do the job.

Free the factor 2


You can mix and match RPG III style, RPG IV fixed-form style, and RPG IV free-form style in your
C-specs, but the result is inconsistent and difficult to read. Take full advantage of the more natural
order and expanded space afforded by the free-form specification (or, previous to Version 5, the
extended Factor 2). When you are coding loops and groups, you find that the code looks and feels
better in free-form.
Use free-form expressions (or EVAL) wherever possible. Instead of Z-ADD and Z-SUB, use
assignment expressions. Use expressions for any arithmetic in your program. Instead of CAT
and SUBST, use string expressions. Use expressions to set indicators (if you need them).
But do not completely abandon columnar alignment as a tool to aid readability in expressions.
Especially when an expression must continue onto subsequent lines, align the expression to
make it easier to understand (refer to Chapter 7 for examples).

Character string manipulation


IBM has greatly enhanced RPG IV’s ability to easily manipulate character strings. Many of the tricks
you had to use with earlier versions of RPG are now obsolete. Modernize your source by exploiting
these new features.
Use a named constant to declare a string constant instead of storing it in an array or
table. Declaring a string (such as a CL command string) as a named constant lets you refer to it
directly instead of forcing you to refer to the string through its array name and index. Use a
named constant to declare any value that you do not expect to change during program
execution.
Avoid using arrays and data structures to manipulate character strings and text. Use the
new string manipulation opcodes, built-in functions, or both instead.
Use free-form assignment expressions whenever possible for string manipulation. When
used with character strings, EVAL is usually equivalent to a MOVEL(P) opcode. When you do
not want the result to be padded with blanks, use %SUBST or %REPLACE functions.
Use variable-length fields to simplify string handling. Use variable-length fields as CONST
or VALUE parameters to every string-handling subprocedure, as well as for work fields. Not only
does the code look better (eliminating the %TRIM function, for example), but it is also faster
than using fixed-length fields. For example, code:

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8


DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++++++++++++++

© Copyright IBM Corp. 2002, 2019 Appendix A. RPG IV style guide A-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

D QualName S 33 VARYING
D Library S 10 VARYING
D File S 10 VARYING
D Member S 10 VARYING

/FREE
QualName = Library + '/' + File + '(' + Member + ')';
/END-FREE

instead of

D QualName S 33
D Library S 10
D File S 10
D Member S 10

/FREE
QualName = %TRIM(Library) + '/' + %TRIM(File)
+ '(' + %TRIM(Member) + ')';
/END-FREE

Avoid obsolescence
RPG is an old language. After 30 years, many of its original, obsolete features are still available. Do
not use them.
Do not sequence program line numbers in columns 1–5. Chances are you never again drop
that deck of punched cards, so the program sequence area is unnecessary. In RPG IV, the columns
are commentary only. You can use them to identify changed lines in a program or structured
indentation levels, but be aware that these columns may be subject to the same hazards as
right-hand comments.
Avoid program-described files. Instead, use externally defined files whenever possible.
If an opcode offers a free-format syntax, use it instead of the fixed-format version. Opcodes
to avoid include CABxx, CASxx, CAT, DO (at V4R4), DOUxx, DOWxx, IFxx, and WHxx. At Version
5, avoid any operation code that the free-form specification does not support (Figure 6.4 in Chapter
6 lists them).
If a BiF offers the same function as an opcode, use the BiF instead of the opcode. With
some opcodes, you can substitute a built-in function for the opcode and use the function within
an expression. At V4R1, the SCAN and SUBST opcodes have virtually equivalent built-in
functions, %SCAN and %SUBST. In addition, you can usually substitute the concatenation
operator (+) in combination with the %TRIMx BiFs in place of the CAT opcode. The free-format
versions are preferable if they offer the same functionality as the opcodes.
Use the date operations to operate on dates. Get rid of the clever date and time routines that
you have gathered and jealously guarded over the years. The RPG IV operation codes and
built-in functions are more efficient, clearer, and more modern. Even if your database includes
dates in legacy formats, you can use the date opcodes to manipulate them.

A-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP Shun obsolete opcodes. In addition to the opcodes mentioned earlier, some opcodes are no
longer supported or have better alternatives:
- CALL, CALLB: The prototyped calls (CALLP or a function call) are just as efficient as CALL
and CALLB and offer the advantages of prototyping and parameter passing by value.
Neither CALL nor CALLB can accept a return value from a procedure.
- DEBUG: With i5/OS (OS/400)’s advanced debugging facilities, this opcode is no longer
supported.
- DSPLY: You should use display file I/O to display information or to acquire input.
- FREE: This opcode is no longer supported.
- PARM, PLIST: If you use prototyped calls, these opcodes are no longer necessary.

Miscellaneous guidelines
Here is an assortment of other style guidelines that can help you improve your RPG IV code.
In all specifications that support keywords, observe a one-keyword-per-line limit. Instead of
spreading multiple keywords and values across the entire specification, your program will be easier
to read and let you more easily add or delete specifications if you limit each line to one keyword, or
at least to closely related keywords (for example, DATFMT and TIMFMT).
Begin all H-spec keywords in column 8, leaving column 7 blank. Separating the keyword from
the required H in column 6 improves readability.
Relegate mysterious code to a well-documented, well-named procedure. Despite your best
efforts, on extremely rare occasions you simply are not able to make the meaning of a chunk of
code clear without extensive comments. By separating such heavily documented, well-tested code
into a procedure, you save future maintenance programmers the trouble of deciphering and dealing
with the code unnecessarily.

Final advice
Sometimes good style and efficient runtime performance do not mix. Wherever you face a conflict
between the two, choose good style. Hard-to-read programs are hard to debug, hard to maintain,
and hard to get right. Program correctness must always win out over speed. Keep in mind these
admonitions from Brian Kernighan and P.J. Plauger’s The Elements of Programming Style:
• Make it right before you make it faster.
• Keep it right when you make it faster.
• Make it clear before you make it faster.
• Do not sacrifice clarity for small gains in efficiency.

© Copyright IBM Corp. 2002, 2019 Appendix A. RPG IV style guide A-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

A-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP
Appendix B. Checkpoint solutions

Unit 1, "RPG IV introduction"

Solutions for Figure 1-18, "Checkpoint (1 of 2)," on page 1-28

Checkpoint solutions (1 of 2)
IBM i

1. True or false: Today’s RPG IV programs must use ILE features such as binding
and subprocedures.
The answer is false.
2. To create a program from an RPGLE type source member, which of the following
answers is correct?
a. CRTRPGPGM
b. CRTBNDRPG
c. CRTRPGMOD and CRTPGM
d. CRTRPGMOD
The answers are CRTBNDRPG and/or CRTRPGMOD and CRTPGM.

3. True or false: To include code from another source member in your RPG IV
program, you would use the /COPY compiler directive.
The answer is true.

© Copyright IBM Corporation 2002, 2014

© Copyright IBM Corp. 2002, 2019 Appendix B. Checkpoint solutions B-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Solutions for Figure 1-19, "Checkpoint (2 of 2)," on page 1-29

Checkpoint solutions (2 of 2)
IBM i

4. Number the following RPG specification types in correct sequence.


1 Control specifications
2 File specifications
3 Definition specifications
4 Input specifications
5 Calculation specifications
6 Output specifications
7 Procedure specifications
The answer is 1 Control specifications, 2 File specifications, 3
Definition specifications, 4 Input specifications, 5 Calculation
specifications, 6 Output specifications, 7 Procedure specifications.

5. A source physical file for RPG IV source members has a ____ byte
record length?
a. 80
b. 92
c. 100
d. 112
The answer is 112.
© Copyright IBM Corporation 2002, 2014

B-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP Unit 2, "Coding specifications for RPG IV"

Solutions for Figure 2-28, "Checkpoint," on page 2-36

Checkpoint solutions
IBM i

1. True or false: A control spec must be coded into every RPG


IV source member.
The answer is false.

2. Which of the following are functions of the file spec in RPG


IV?
a. To reflect the status of the last input operation
b. To designate the file as Input or Output
c. To specify a file as described externally or in the program
The answers are to designate the file as Input or Output and
to specify a file as described externally or in the program.

3. True or false: The Definition specification is NOT needed to


define fields from an externally described file.
The answer is true.

© Copyright IBM Corporation 2002, 2014

© Copyright IBM Corp. 2002, 2019 Appendix B. Checkpoint solutions B-3


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit 3, "Data representation and definition"

Solutions for Figure 3-22, "Checkpoint," on page 3-29

Checkpoint solutions
IBM i

1. True or false: Named indicators are an effective alternative to


numeric indicators as they allow you to use a meaningful
name.
The answer is true.

2. Data is defined in an RPG IV program with:


a. Input specifications and program described files
b. Externally described files
c. Definition specification definitions
d. All of the above
The answer is all of the above.

3. True or false: The Definition spec is NOT needed to define


fields from an externally described file.
The answer is true.

© Copyright IBM Corporation 2002, 2014

B-4 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP Unit 4, "Manipulating data in calculations"

Solutions for Figure 4-42, "Checkpoint," on page 4-53

Checkpoint solutions
IBM i

1. Given the following values for the variables, what will be the value of X
after the Eval statement?
A = 1, B = 2, C = 3
Eval X = A * B + C ** B - 1
The answer is 10.

2. Given the same initial values for the variables A, B, and C, what will be
the value of X after this Eval statement?
Eval X = A * B + C ** (B – 1)
The answer is 5.

3. Given the same initial values for the variables A, B, and C, and given
that *IN03 is ON, what will be the value of *INLR after this Eval
statement?
Eval *INLR = *IN03 AND B > A OR C > A + B
The answer is *INLR = ‘1’.
© Copyright IBM Corporation 2002, 2014

© Copyright IBM Corp. 2002, 2019 Appendix B. Checkpoint solutions B-5


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit 5, "Using printer and display files in an RPG IV program"

Solutions for Figure 5-15, "Checkpoint," on page 5-23

Checkpoint solutions
IBM i

1. True or false: Exact line numbers can be used to position a


particular field or constant on the report.
The answer is true.

2. Which of the following DDS facilities are available when


defining printer files?
a. Continuation lines
b. Edit codes and words
c. Field definition referencing
d. All of the above
The answer is all of the above.

3. What are the three levels at which DDS printer file keywords
can be specified?
The answers are file, record, and field.
© Copyright IBM Corporation 2002, 2014

B-6 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP Solutions for Figure 5-35, "Checkpoint," on page 5-46

Checkpoint solutions
IBM i

1. True or false: For interactive inquiry, display record formats must use
the same field names as the database file being processed.
The answer is false.

2. Which of the following are used to validate data entry fields?


a. CHECK
b. DSPATR
c. RANGE
d. All of the above
The answers are CHECK and RANGE.

3. True or false: An inquiry program requires at least two display record


formats.
The answer is false.

© Copyright IBM Corporation 2002, 2014

© Copyright IBM Corp. 2002, 2019 Appendix B. Checkpoint solutions B-7


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit 6, "Structured programming, error handling,


subprocedures, and subroutines"

Solutions for Figure 6-46, "Checkpoint," on page 6-60

Checkpoint solutions
IBM i

1. True or false: The parameter list in both the calling and the
called programs must match field name by field name.
The answer is false.
2. Which of the following opcodes does not have a
corresponding Endxx statement to terminate the group?
a. Do
b. If
c. Plist
d. BegSR
e. Select
The answer is Plist.
3. True or false: An RPG subroutine can be called from another
program outside of where it is written by coding an ExSR.
The answer is false.

© Copyright IBM Corporation 2002, 2014

B-8 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

AP Unit 7, "Using arrays, data structures, and data areas"

Solutions for Figure 7-39, "Checkpoint," on page 7-45

Checkpoint solutions
IBM i

1. Data structures:
a. Occupy storage
b. Are character strings
c. Can be internally or externally described
d. All of the above
The answer is all of the above.

2. True or false: Data areas can be used to communicate


between processes.
The answer is true.

3. True or false: Use the %LookUpEQ BiF to find items in an


array.
The answer is false.

© Copyright IBM Corporation 2002, 2014

© Copyright IBM Corp. 2002, 2019 Appendix B. Checkpoint solutions B-9


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Unit 8, "Accessing the DB2 database using RPG IV"

Solutions for Figure 8-48, "Checkpoint," on page 8-57

Checkpoint solutions
IBM i

1. True or false: A logical file contains a copy of the data in the physical
file.
The answer is false.

2. Database files can be specified (usage keyword on the Dcl-f


specification) as which of the following types?
a. *Input
b. *Output
c. *Combined
d. *Update
The answers are *Input, *Output, and *Update.

3. True or false: SetLL and SetGT are used to position the file cursor
before sequential read operations.
The answer is true.
© Copyright IBM Corporation 2002, 2014

Unit 9, "What’s next?"


No checkpoint solutions in this unit.

B-10 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0
Student Notebook

bibl
Bibliography
Manuals:
IBM Rational Development Studio for i ILE RPG Language Reference
IBM Rational Development Studio for i ILE RPG Programmer’s Guide

Other reference manuals on CD or information center:


DDS Reference: Physical and Logical Files
Display Files
Printer Files
ILE Concepts
ILE Application Development Example
ADTS/400: Screen Design Aid

Web URLs:
http://publib.boulder.ibm.com/infocenter/iseries/v7r1m0/index.jsp
IBM i Information Center (V7R1)
http://www.redbooks.ibm.com Internet site for ITSO Redbooks
http://www.ibm.com IBM’s Internet Connection web site
http://www.rfc-editor.org/ Internet “Requests for Comments” Editor
http://www.midrange.com Midrange lists and forums
http://www.iprodeveloper.com/ Home of System i Network and Magazine

CD-ROMs:
SK3T-4091 IBM i Information Center (Version 7)

ITSO Redbooks
SG24-5402 Who Knew You Could Do That with RPG IV?

Other useful web sites


Certification: http://www.ibm.com/certify
MidRange News i Community http://www.midrangenews.com/

© Copyright IBM Corp. 2002, 2019 Bibliography X-1


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


Student Notebook

Articles:
News/400 (June 98) “The Essential RPG IV Style Guide” (updated summer 2000)
News/400 (Sept 00) “RPG IV Style Guide: Error Recovery”
News/400 (Nov 00) “RPG IV: Free Format and More”

X-2 RPG IV Programming Fundamentals © Copyright IBM Corp. 2002, 2019


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.

Licensed to Mario Rodriguez for class on 1/25/2021


V10.0

backpg
Back page

Licensed to Mario Rodriguez for class on 1/25/2021


Licensed to Mario Rodriguez for class on 1/25/2021

You might also like