COBOL IF-ELSE Statement is used for conditional processing in COBOL.
IF-ELSE
IF-ELSE performs the various set of tasks-
- The statement inside the IF block will execute if the condition of IF statement is true
- The statement inside IF block will not execute when the condition of IF statement is false. If we code ELSE block, in this case, the statement will execute
- Nesting of ‘IF-ELSE’ statements can be done that means one or more ‘IF-ELSE’ statements can be coded inside an ‘IF-ELSE’ statement
Syntax
IF condition
[statement-1/s]ELSE
[statement-2/s]
END-IF
Most used IF Format/Example 1
IF condition-is-true
{Statement/s}
END-IF.
Example:
IF MALE
DISPLAY “HE IS A MALE”
END-IF.
Most used IF-ELSE Format/Example 2
IF condition-is-true
{Statement/s}/{CONTINUE/NEXT SENTENCE}
ELSE
{Statement/s}{CONTINUE/NEXT SENTENCE}
END-IF.
Example:
IF MALE
DISPLAY “HE IS A MALE”
ELSE
DISPLAY “SHE IS A FEMALE”
END-IF.
IF NOT MALE
DISPLAY “SHE IS A FEMALE”
ELSE
DISPLAY “HE IS A MALE”
END-IF.
IF A = B
DISPLAY “BOTH ARE EQUAL”
ELSE
DISPLAY “BOTH ARE NOT EQUAL”
END-IF.
IF A IS EQUAL TO B
DISPLAY “BOTH ARE EQUAL”
ELSE
DISPLAY “BOTH ARE NOT EQUAL”
END-IF.
IF A = B
DISPLAY “BOTH ARE EQUAL”
ELSE
DISPLAY “BOTH ARE NOT EQUAL”
END-IF.
IF A IS NOT EQUAL TO B
DISPLAY “BOTH ARE NOT EQUAL”
ELSE
DISPLAY “BOTH ARE EQUAL”
END-IF.
IF A > B
DISPLAY “A IS GREATER”
ELSE
DISPLAY “B IS GREATER”
END-IF.
IF A IS NEGATIVE
DISPLAY “NEGATIVE”
ELSE
DISPLAY “POSITIVE”
END-IF.
IF A IS NUMERIC
MOVE 9 TO A
ELSE
DISPLAY “A IS NOT NUMERIC”
END-IF.
Most used Nested IF-ELSE Format/Example 3
IF condition-is-true
{Statement/s}/{CONTINUE/NEXT SENTENCE}
IF condition-is-true
{Statement/s}/{CONTINUE/NEXT SENTENCE}
ELSE
{Statement/s}{CONTINUE/NEXT SENTENCE}
END-IF
ELSE
IF condition-is-true
{Statement/s}/{CONTINUE/NEXT SENTENCE}
ELSE
{Statement/s}{CONTINUE/NEXT SENTENCE}
END-IF
END-IF.
Example:
IF A = 5 AND B = 10
DISPLAY “RIGHT VALUES”
MOVE 15 TO C
ELSE
IF A = 5
MOVE 10 TO B
ELSE
MOVE 5 TO A
END-IF
END-IF.