Signed Fields
Part of the Data and Numbers section of Coddy's COBOL Programming journey. Lesson 5 of 23.
A PIC 9 field has no sign. A negative result loses its minus and keeps only the digits:
01 BALANCE PIC 9(3) VALUE 50.
SUBTRACT 80 FROM BALANCE. *> 030An S at the start of the picture lets a field hold a sign. It adds no digit:
01 BALANCE PIC S9(3) VALUE 50.
SUBTRACT 80 FROM BALANCE. *> -30The sign is kept in the byte of the last digit, so the field is still 3 bytes. GnuCOBOL's DISPLAY prints it after the digits: 030- for -30 and 030+ for 30. An IBM mainframe shows that last byte as another character instead, like 03} for -30.
SIGN IS LEADING SEPARATE gives the sign a byte of its own, in front. DISPLAY then prints -030, and the field is one byte longer:
01 BALANCE PIC S9(3)
SIGN IS LEADING SEPARATE.Challenge
EasyBALANCE starts at 50 and the program subtracts the withdrawal typed. A withdrawal of 80 prints 030, as if 30 were left. Change the picture of BALANCE so it keeps the sign and prints 030-.
Example input, one line per ACCEPT: 80.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. WITHDRAW.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 BALANCE PIC 9(3) VALUE 50.
01 WITHDRAWAL PIC 9(3).
PROCEDURE DIVISION.
ACCEPT WITHDRAWAL.
SUBTRACT WITHDRAWAL FROM BALANCE.
DISPLAY BALANCE.
STOP RUN.