Conditional Expressions
- A conditional expression is a condition or a part of a condition that evaluates either TRUE or FALSE.
- These are used to choose the execution flow based on the truth value of the condition.
- These are used in decision-making statements (IF, IF...ELSE, EVALUATE) and looping statements (PERFORM and SEARCH).
- Simple and complex conditions are enclosed with closed parentheses () if required.
Conditional expressions are categorized into two types -
- Simple conditions
- Combined conditions
Simple conditions -
A simple condition compares two operands using an operator. There are five types of simple conditions -
CLASS condition tests whether the data in a variable belongs to a specific category of characters such as ALPHABETIC, ALPHABETIC-LOWER, ALPHABETIC-UPPER, NUMERIC, etc. For example -
IF WS-VAR IS NUMERIC
...
END-IF.
A relation condition compares two operands using relational operators (=, >, <, <=, >=, <>) and returns a boolean value of TRUE or FALSE. For example -
IF WS-VAR1 = WS-VAR2
...
END-IF.
SIGN condition tests the sign (positive, negative, or zero) of the data in numeric variables. For example -
IF WS-VAR IS NEGATIVE
...
END-IF.
A condition name is a meaningful name for a value or a range of values of a variable. The IF and EVALUATE statements validate whether the condition variable's value is equal to any values associated with the condition name.For example -
01 WS-VAR PIC X(01).
88 WS-MALE VALUE "M".
...
IF WS-MALE
...
END-IF.
Combined conditions
A Combined condition combines two or more simple conditions using AND or OR. Each logical operator must be preceded and followed by a space.
It combines two or more simple conditions using AND. The truth value is true when both conditions are true. Example -
IF (WS-A > WS-B) AND (WS-C < WS-D)
...
END-IF.
It combines two or more simple conditions using OR. The truth value is true when atleast one condition is true. Example -
IF (WS-A > WS-B) OR (WS-C < WS-D)
...
END-IF.
NOT Condition -
A NOT condition checks for the negated truth value of the condition. For Example, if the truth value of the condition is true, then the truth value of same negated condition is false and vice versa.
IF NOT (WS-A = WS-B)
...
END-IF.
Truth Table
Let us assume condition1 (C1) and condition2 (C2). The table below shows the true value of AND, OR, and NOT logical operators -
C1 | C2 | C1 AND C2 | C1 OR C2 | NOT C1 | NOT C2 |
---|---|---|---|---|---|
True | True | True | True | False | False |
False | True | False | True | True | False |
True | False | False | True | False | True |
False | False | False | False | True | True |
Operators precedence -
The operators evaluating order from highest to lowest is -
- Arithmetic operators (+, -, *, /, **)
- Simple conditions - ()
- NOT
- AND
- OR