Control Structures: Conditional Statements and Loops

August 24, 2024

Control Structures: Conditional Statements and Loops

In this lesson, we explore control structures in ABAP. Control structures are essential for controlling the flow of your programs based on certain conditions or repetitive tasks. They allow your programs to make decisions and execute code selectively, which is fundamental in programming.

Conditional Statements

Conditional statements allow you to execute certain parts of your code based on specific conditions. In ABAP, the most commonly used conditional statements are IF and CASE.

IF Statement

The IF statement evaluates a condition and executes a block of code if the condition is true. The syntax is as follows:

IF .
  <! Execute this block if the condition is true>
ENDIF.

Here’s an example of an IF statement in ABAP:

DATA: lv_value TYPE i.

lv_value = 10.

IF lv_value > 5.
  WRITE: 'Value is greater than 5'.
ENDIF.

CASE Statement

The CASE statement is useful when you have multiple conditions to evaluate based on the same variable. The syntax is as follows:

CASE .
  WHEN .
    <! Execute this block if variable equals value1>
  WHEN .
    <! Execute this block if variable equals value2>
  ...
  WHEN OTHERS.
    <! Execute this block if none of the above conditions are met>
ENDCASE.

Here’s an example of a CASE statement:

DATA: lv_day TYPE i.

lv_day = 3.

CASE lv_day.
  WHEN 1.
    WRITE: 'Monday'.
  WHEN 2.
    WRITE: 'Tuesday'.
  WHEN 3.
    WRITE: 'Wednesday'.
  WHEN OTHERS.
    WRITE: 'Not a valid day'.
ENDCASE.

Loops

Loops are used to execute a block of code repeatedly until a certain condition is met. In ABAP, the most commonly used loops are DO and WHILE.

DO Loop

The DO loop executes a block of code a specific number of times. The syntax is as follows:

DO  TIMES.
  <! Execute this block repeatedly>
ENDDO.

Here’s an example of a DO loop:

DATA: lv_counter TYPE i.

DO 5 TIMES.
  lv_counter = sy-index.
  WRITE: / 'Counter value:', lv_counter.
ENDDO.

WHILE Loop

The WHILE loop continues to execute as long as a specified condition is true. The syntax is as follows:

WHILE .
  <! Execute this block as long as the condition is true>
ENDWHILE.

Here’s an example of a WHILE loop:

DATA: lv_counter TYPE i.

lv_counter = 1.
WHILE lv_counter <= 5.
  WRITE: / 'Counter value:', lv_counter.
  lv_counter = lv_counter + 1.
ENDWHILE.

Conclusion

In this lesson, we covered the essential control structures in ABAP, including conditional statements like IF and CASE, as well as loops such as DO and WHILE. Mastering these structures will enable you to write more dynamic and responsive ABAP programs. In the next lesson, we will delve deeper into error handling and debugging techniques in ABAP.