SAP ABAP - If...Else Statement



In case of IF….ELSE statements, if the expression evaluates to true then the IF block of code will be executed. Otherwise, ELSE block of code will be executed.

The following syntax is used for IF….ELSE statement.

IF<condition_1>.  
   <statement block 1>.  
ELSE.   
   <statement block 2>.  
ENDIF.

Flow Diagram

If Else Statement

Example

Report YH_SEP_15.
  
Data Title_1(20) TYPE C.  
     Title_1 = 'Tutorials'.
	
IF Title_1 = 'Tutorial'.  
   write 'This is IF Statement'.  
ELSE.  
   write 'This is ELSE Statement'.
  
ENDIF.

The above code produces the following output −

This is ELSE Statement.

IF….ELSEIF….ELSE Statement

Sometimes nesting of the IF statements can make the code difficult to understand. In such cases, the ELSEIF statement is used to avoid nesting of the IF statement.

When using IF, ELSEIF and ELSE statements there are a few points to consider −

  • An IF statement can have zero or one ELSE statement and it must come after any ELSEIF statement.

  • An IF statement can have zero to many ELSEIF statements and they must come before the ELSE statement.

  • If an ELSEIF statement succeeds, none of the remaining ELSEIF statements or ELSE statement will be tested.

The following syntax is used for the IF....ELSEIF….ELSE statement.

IF<condition_1>.
  
<statement block 1>.
  
ELSEIF<condition_2>.
  
<statement block 2>.
  
ELSEIF<condition_3>. 
 
<statement block 3>. 
...... 
...... 
...... 
...... 
ELSE.
  
<statement block>.  

ENDIF.

In the above syntax, the execution of the processing block is based on the result of one or more logical conditions associated with the processing block. Here −

  • condition_1 of IF statement represents a logical condition that evaluates a true or false condition.

  • condition_2 shows the second condition specified in the ELSEIF statement, which is executed when the IF statement condition turns out to be false.

  • ENDIF denotes the end of the IF statement block.

Example

Report YH_SEP_15.  
Data Result TYPE I VALUE 65.  
   IF Result < 0.  
	
Write / 'Result is less than zero'.  
   ELSEIF Result < 70.  
	
Write / 'Result is less than seventy'.  
ELSE.  

Write / 'Result is greater than seventy'.
  
   ENDIF.

The above code produces the following output −

Result is less than seventy.
sap_abap_decisions.htm
Advertisements