Chuyển đến nội dung chính
eLearner.app
Mô-đun 2 · Bài học 2 trong tổng số 24/10 trong khóa học~12 min
Bài học theo mô-đun (2/2)

Quyết định với IF và ĐÁNH GIÁ

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

tập thể dục#cobol.m2.l2.e1
Nỗ lực: 0Đang tải…

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.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử

tập thể dục#cobol.m2.l2.e2
Nỗ lực: 0Đang tải…

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'.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử