Control structures in ABAP (Advanced Business Application Programming) are essential constructs that enable you to control the flow of your program's execution. These structures include conditional statements and looping constructs. Here's an overview of control structures in ABAP:
1. Conditional Statements:
Conditional statements allow you to execute different blocks of code based on specified conditions. ABAP provides the following conditional statements:
IF Statement: The IF statement is used to perform a specific action if a condition is true.
DATA lv_value TYPE i VALUE 42. IF lv_value > 30. WRITE 'Value is greater than 30'. ENDIF.
ELSE and ELSEIF Clauses: You can use the ELSE clause to specify an alternative action when the IF condition is false. Additionally, you can use ELSEIF to evaluate multiple conditions.
DATA lv_value TYPE i VALUE 20. IF lv_value > 30. WRITE 'Value is greater than 30'. ELSE. WRITE 'Value is not greater than 30'. ENDIF.
CASE Statement: The CASE statement allows you to perform different actions based on the value of a variable.
DATA lv_grade TYPE c LENGTH 1 VALUE 'A'. CASE lv_grade. WHEN 'A'. WRITE 'Excellent'. WHEN 'B'. WRITE 'Good'. WHEN OTHERS. WRITE 'Not specified'. ENDCASE.
2. Looping Constructs:
Looping constructs enable you to repeat a block of code multiple times. ABAP offers several looping structures:
DO Loop: The DO loop is a basic loop structure that repeatedly executes a block of code as long as a specified condition is true.
DATA lv_counter TYPE i VALUE 1. DO 5 TIMES. WRITE lv_counter. ADD 1 TO lv_counter. ENDDO.
WHILE Loop: The WHILE loop repeats a block of code while a specified condition is true.
DATA lv_value TYPE i VALUE 1. WHILE lv_value <= 5. WRITE lv_value. ADD 1 TO lv_value. ENDWHILE.
FOR Loop: The FOR loop is used for iterating over a range of values.
DATA lv_total TYPE i VALUE 0. DO 5 TIMES. lv_total = lv_total + sy-index. ENDDO. WRITE lv_total.
LOOP AT: The LOOP AT statement is used to iterate through internal tables.
DATA: lt_numbers TYPE TABLE OF i, lv_total TYPE i.
APPEND 1 TO lt_numbers. APPEND 2 TO lt_numbers. APPEND 3 TO lt_numbers.
LOOP AT lt_numbers INTO lv_total. WRITE lv_total. ENDLOOP.
EXIT Statement: The EXIT statement allows you to exit a loop prematurely when a certain condition is met.
DATA lv_value TYPE i VALUE 1. DO 10 TIMES. IF lv_value > 5. EXIT. ENDIF. WRITE lv_value. ADD 1 TO lv_value. ENDDO.