GO TO and Why Not
Part of the Decisions and Loops section of Coddy's COBOL Programming journey. Lesson 16 of 20.
GO TO jumps to a paragraph and does not come back. Older programs built their loops from it:
LOOP-PARA.
DISPLAY I.
ADD 1 TO I.
IF I <= N
GO TO LOOP-PARA
END-IF.To follow such a program, a reader has to find every GO TO that lands on each paragraph. A program full of jumps is called spaghetti code, and it is hard to change safely.
A PERFORM always comes back to the line after it, so the flow reads from top to bottom. The same loop without a jump:
PERFORM VARYING I FROM 1 BY 1 UNTIL I > N
DISPLAY I
END-PERFORM.Most coding standards keep GO TO out of new code, but older programs still use it, often as PERFORM A-PARA THRU A-EXIT with a GO TO A-EXIT to leave the range early.
Challenge
EasyThis GO TO loop tests at the bottom, so for 0 it still prints 01. Replace LOOP-PARA with an inline PERFORM VARYING so 0 prints only Done.
Example input, one line per ACCEPT: 3.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. LISTNUM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 N PIC 9.
01 I PIC 99.
PROCEDURE DIVISION.
MAIN-PARA.
ACCEPT N.
MOVE 1 TO I.
LOOP-PARA.
DISPLAY I.
ADD 1 TO I.
IF I <= N
GO TO LOOP-PARA
END-IF.
DISPLAY "Done".
STOP RUN.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Decisions and Loops
3Paragraphs and Loops
Paragraphs and PERFORMPERFORM TIMESPERFORM UNTILPERFORM VARYINGInline PERFORMGO TO and Why NotPractice on your own: Online COBOL compiler