Let's understand Mainframe
Home Tutorials Interview Q&A Quiz Mainframe Memes Contact us About us

MODULE 7: COBOL Control statements


IF statement

  • Simple form of IF statement already explained in Module-6
  • The general form of IF statement is as follows:-

    IF condition THEN <statement-block-1> ELSE <statement-block-2> END-IF.

  • The IF statement is COBOL’S branch statement. It can be used to route program execution through two different paths
  • In above general format, each statement-block may contain one or more statement. The condition is any expression that returns either true or false.
  • The IF works like this:-
    • IF condition is true, statement-block-1 will be executed; otherwise, statement-block-2 will be executed. In no case will both statement be executed
  • ELSE part is optional to specify
  • END-IF is scope-terminator. If statement ends with this scope-terminator. Instead of END-IF, we can use period. However, structured programming promotes use of END-IF over period.
  • Example:-

    IF WS-A > WS-B DISPLAY ‘WS-A IS GREATER’ ELSE DISPLAY ‘WS-B IS GREATER’ END-IF. DISPLAY ‘WS-A: ‘ WS-A DISPLAY ‘WS-B: ‘ WS-B

  • Below flow chart will help you understand example given above:-

Nested IF statement

  • COBOL allows to code IF statement inside another IF or ELSE. Such hierarchy of IF’s are referred to as Nested IF’s. Nested IF’s are very common in programming
  • When you nest IF’s, the main thing to remember is that an ELSE statement always refer to the nearest IF statement that is within the same block as the ELSE and that is not already associated with another ELSE.
  • Since, the ELSE phrase is optional, a nested IF statement may have fewer ELSE’s than IF’s
  • To avoid confusion and better readability, it is suggested to code the IF’s with proper indentation and one END-IF for every IF.
  • Example:-

    IF WS-A IS NUMERIC IF WS-A IS ZERO DISPLAY ‘WS-A VALUE IS ZERO’ ELSE IF WS-A IS > 10 DISPLAY ‘WS-A VALUE IS GREATER THAN 10’ ELSE DISPLAY ‘WS-A VALUE IS LESS THAN 10’ END-IF END-IF ELSE DISPLAY ‘WS-A IS NON-NUMERIC’ END-IF. DISPLAY ‘CAME OUT OF NESTED IF’

  • Below flow chart will help you understand example given above:-






© copyright mainframebug.com
Privacy Policy