メインコンテンツにスキップ
eLearner.app
モジュール 2 · レッスン 2 / 2コース内の 4/10~12 min
モジュールのレッスン (2/2)

IF と EVALUATE による決定

Decision making in COBOL is performed primarily using the IF conditional statement and the multi-branch selection structure EVALUATE (analogous to switch or match in modern languages).

The IF Conditional Statement

The fundamental syntax of the IF statement is:

Code
IF condition
    statements-if-true
ELSE
    statements-if-false
END-IF.

In modern COBOL versions (COBOL-85 and later), the statement must explicitly end with END-IF. instead of relying solely on the final period ., significantly reducing parsing and logic errors.

Common Conditions

  • Greater than: > or GREATER THAN
  • Less than: < or LESS THAN
  • Equal to: = or EQUAL TO
  • Greater than or equal to: >= or GREATER THAN OR EQUAL TO
  • Less than or equal to: <= or LESS THAN OR EQUAL TO
Code
IF WS-BALANCE < 0
    DISPLAY "OVERDRAWN"
ELSE
    DISPLAY "ACCOUNT ACTIVE"
END-IF.

The EVALUATE Statement

When we need to compare a variable against multiple discrete values, nested IF statements can become complex. The EVALUATE statement resolves this by structuring the choices in a clean way:

Code
EVALUATE WS-USER-ROLE
    WHEN "ADMIN"
        DISPLAY "FULL ACCESS"
    WHEN "EDITOR"
        DISPLAY "EDIT ACCESS"
    WHEN OTHER
        DISPLAY "LIMITED ACCESS"
END-EVALUATE.
  • WHEN OTHER: Identifies the fallback branch (equivalent to default or the final else in modern languages).
  • END-EVALUATE.: Closes the structure.

Try it yourself

運動#cobol.m2.l2.e1
試行回数: 0読み込み中…

Write an IF-ELSE-END-IF block that checks if the variable WS-USER-AGE is greater than or equal to 18. If true, print 'ADULT', otherwise print 'MINOR' using DISPLAY.

エディターを読み込み中…
ヒントを表示

Use >= for the comparison, DISPLAY for output, and END-IF. (with the dot at the end of the block).

3 回の試行後に解決策が利用可能になります

運動#cobol.m2.l2.e2
試行回数: 0読み込み中…

Complete the EVALUATE structure to check the WS-STATUS variable. If the value is 'A' print 'ACTIVE', if it is 'I' print 'INACTIVE', otherwise for any other value print 'UNKNOWN'.

エディターを読み込み中…
ヒントを表示

Write each WHEN branch followed by its DISPLAY, and use WHEN OTHER to handle the fallback.

3 回の試行後に解決策が利用可能になります