DO Loop in ABAP: A Beginner's Guide with Examples
Table of Contents
- • What is a DO Loop in ABAP?
- • Why Do We Need a DO Loop?
- ↳ Simple Loop Code in ABAP Editor:
- • Basic Syntax
- • Understanding the SY-INDEX System Variable
- • Unconditional Infinite Loops: DO. without TIMES
- ↳ Why Use Infinite Loops?
- • Generating Sequential Employee IDs
- • Performing Calculations with a DO Loop
- ↳ Sum Loop Code inside ABAP Editor:
- ↳ Program Execution Output:
- • Practical Business Use Case: String Parsing & Tokenization
- • Practical Business Use Case: Internal Table Iteration by Index
- • Controlling Loop Execution (EXIT, CONTINUE, CHECK)
- ↳ 1. The EXIT Statement
- ↳ 2. The CONTINUE Statement
- ↳ 3. The CHECK Statement
- • Nested DO Loops & System Variable Caching
- • Modern ABAP 7.40+ Alternatives to DO Loops
- ↳ Traditional DO Loop Approach:
- ↳ Modern ABAP 7.40+ FOR Expression:
- • Comparison Matrix: DO vs. WHILE vs. LOOP AT vs. FOR
- • Self-Assessment Checkpoint
- • Common Errors & Best Practices
- • Summary
![]()
When developing application logic in SAP ABAP, you will frequently need to execute a specific block of code multiple times. Writing the same statements repeatedly would make your program unnecessarily long, difficult to read, and complex to update.
To solve this problem, ABAP offers looping structures. The DO loop is one of the most fundamental loop controls, enabling you to repeat operations a fixed number of times.
Loops are a critical part of SAP database reporting, batch data transfers, mathematical calculations, and business validations. In this guide, we will break down the DO loop with practical examples.
What is a DO Loop in ABAP?
A DO loop is an unconditional loop structure that repeats a block of code a specified number of times.
The block of code starts with the DO statement and ends with the ENDDO keyword. The system repeats everything contained between these two boundaries until the specified iteration count is reached or a loop control statement terminates it.
Why Do We Need a DO Loop?
Imagine you need to print a developer message five times on a report list:
Without a loop, you would write:
WRITE / 'Welcome to SAP ABAP Academy'.
WRITE / 'Welcome to SAP ABAP Academy'.
WRITE / 'Welcome to SAP ABAP Academy'.
WRITE / 'Welcome to SAP ABAP Academy'.
WRITE / 'Welcome to SAP ABAP Academy'.
This works, but it scales poorly. If you needed to repeat this a hundred times, it would become unmanageable. By wrapping it in a DO loop, you achieve the same output with cleaner code:
DO 5 TIMES.
WRITE / 'Welcome to SAP ABAP Academy'.
ENDDO.
Simple Loop Code in ABAP Editor:

Basic Syntax
The syntax for a standard DO loop is:
DO n TIMES.
" Statements to be executed
ENDDO.
DO n TIMES: Initiates the loop, wherenis a number, variable, or expression indicating the iteration count.ENDDO: Closes the loop block.
Understanding the SY-INDEX System Variable
During loop execution, the SAP system maintains a special system field named SY-INDEX. This system variable stores the index of the current loop iteration. It starts at 1 for the first run and increments by 1 with each repeat.
Let’s look at an example showing SY-INDEX in action:
REPORT z_do_index_demo.
DO 5 TIMES.
WRITE / sy-index.
ENDDO.
Output:
1
2
3
4
5
This indexing is extremely useful for generating lists of sequential ID numbers, processing internal arrays, or running mathematical calculations.
Unconditional Infinite Loops: DO. without TIMES
If you omit the n TIMES addition, the DO statement creates an unconditional infinite loop:
DO.
" This loop executes infinitely unless terminated by EXIT
IF condition_met = abap_true.
EXIT.
ENDIF.
ENDDO.
Why Use Infinite Loops?
Infinite DO loops are used when the exact number of iterations is unknown before runtime — such as reading a sequential file line-by-line until the End-Of-File (EOF) marker is reached, or consuming external interface buffer streams until no further records remain.
⚠️ Warning: Always ensure an unconditional
DO.loop contains a guaranteedEXITcondition. If the exit condition is never triggered, the program will lock the dialog work process until SAP throws aTIME_OUTruntime error (Short dump:TIME_OUT).
Generating Sequential Employee IDs
Here is an example showing how to use SY-INDEX to generate dummy employee numbers:
REPORT z_employee_id_generator.
DATA lv_emp_id TYPE i.
DO 5 TIMES.
lv_emp_id = 1000 + sy-index.
WRITE: / 'Generated Employee ID:', lv_emp_id.
ENDDO.
Output:
Generated Employee ID: 1001
Generated Employee ID: 1002
Generated Employee ID: 1003
Generated Employee ID: 1004
Generated Employee ID: 1005
Performing Calculations with a DO Loop
Loops are frequently used to compute running totals and process numeric arrays. Here is a practical example showing how to sum numbers from 1 to 10:
REPORT z_sum_demo.
DATA lv_total TYPE i.
DO 10 TIMES.
lv_total = lv_total + sy-index.
ENDDO.
WRITE: 'Total = ', lv_total.
Sum Loop Code inside ABAP Editor:

Program Execution Output:

Practical Business Use Case: String Parsing & Tokenization
Before expressions like SPLIT or regex helpers were added to ABAP, developers used DO loops to parse comma-separated string records or extract characters token by token:
REPORT z_parse_string_demo.
DATA: gv_raw_string TYPE string VALUE 'SAP,ABAP,Fiori,HANA,BTP',
gv_char TYPE c LENGTH 1,
gv_offset TYPE i VALUE 0,
gv_length TYPE i,
gv_word TYPE string.
gv_length = strlen( gv_raw_string ).
DO gv_length TIMES.
gv_offset = sy-index - 1.
gv_char = gv_raw_string+gv_offset(1).
IF gv_char = ','.
WRITE: / 'Extracted Token:', gv_word.
CLEAR gv_word.
ELSE.
CONCATENATE gv_word gv_char INTO gv_word.
ENDIF.
ENDDO.
" Print final remaining word after loop ends
IF gv_word IS NOT INITIAL.
WRITE: / 'Extracted Token:', gv_word.
ENDIF.
Practical Business Use Case: Internal Table Iteration by Index
While LOOP AT itab is the standard way to iterate internal tables, DO loops combined with READ TABLE ... INDEX are occasionally used when you need to step through table records with custom index steps:
REPORT z_do_read_table.
TYPES: BEGIN OF ty_sales,
vbeln TYPE vbeln_va,
netwr TYPE netwr_ak,
END OF ty_sales.
DATA: gt_sales TYPE TABLE OF ty_sales,
gs_sales TYPE ty_sales.
" Populate sample data
APPEND VALUE #( vbeln = '0000001001' netwr = '1500.00' ) TO gt_sales.
APPEND VALUE #( vbeln = '0000001002' netwr = '2800.50' ) TO gt_sales.
APPEND VALUE #( vbeln = '0000001003' netwr = '4200.00' ) TO gt_sales.
" Iterate table records using DO loop and SY-INDEX
DO lines( gt_sales ) TIMES.
READ TABLE gt_sales INTO gs_sales INDEX sy-index.
IF sy-subrc = 0.
WRITE: / 'Doc:', gs_sales-vbeln, 'Amount:', gs_sales-netwr.
ENDIF.
ENDDO.
Controlling Loop Execution (EXIT, CONTINUE, CHECK)
You can alter the flow of a DO loop using three control keywords:
1. The EXIT Statement
The EXIT statement terminates the entire loop execution instantly. The program stops iterating and jumps to the code following ENDDO.
DO 10 TIMES.
IF sy-index = 5.
EXIT.
ENDIF.
WRITE / sy-index.
ENDDO.
Output:
1
2
3
4
(The loop exits as soon as index reaches 5).
2. The CONTINUE Statement
The CONTINUE statement terminates the current loop iteration immediately. It ignores any remaining lines of code in the current iteration and starts the next iteration at the top of the loop.
DO 5 TIMES.
IF sy-index = 3.
CONTINUE.
ENDIF.
WRITE / sy-index.
ENDDO.
Output:
1
2
4
5
(The value 3 is skipped).
3. The CHECK Statement
The CHECK statement evaluates a logical condition. If the condition is true, the loop continues. If the condition is false, the loop skips the remaining statements in the current iteration (equivalent to CONTINUE).
DO 6 TIMES.
CHECK sy-index MOD 2 = 0.
WRITE / sy-index.
ENDDO.
Output:
2
4
6
(Only even iteration indexes are printed).
Nested DO Loops & System Variable Caching
You can write loops inside other loops (nested loops) to process multi-dimensional data grids.
⚠️ Important System Field Rule:
SY-INDEXalways refers to the current active loop. When an inner loop starts,SY-INDEXgets overwritten by the inner loop count. If you need the outer loop index inside the inner loop, cache it in a local variable beforehand!
REPORT z_nested_loops_demo.
DATA: gv_outer_index TYPE i.
DO 3 TIMES.
gv_outer_index = sy-index. " Cache outer loop index!
WRITE: / 'Outer Loop Iteration:', gv_outer_index.
DO 2 TIMES.
WRITE: / ' Inner Loop Iteration:', sy-index,
' (Parent Outer:', gv_outer_index, ')'.
ENDDO.
ENDDO.
Output:
Outer Loop Iteration: 1
Inner Loop Iteration: 1 (Parent Outer: 1 )
Inner Loop Iteration: 2 (Parent Outer: 1 )
Outer Loop Iteration: 2
Inner Loop Iteration: 1 (Parent Outer: 2 )
Inner Loop Iteration: 2 (Parent Outer: 2 )
Outer Loop Iteration: 3
Inner Loop Iteration: 1 (Parent Outer: 3 )
Inner Loop Iteration: 2 (Parent Outer: 3 )
Modern ABAP 7.40+ Alternatives to DO Loops
In modern ABAP 7.40 and S/4HANA programming, traditional DO loops can often be replaced by inline FOR Expressions inside constructor operators like VALUE or REDUCE:
Traditional DO Loop Approach:
DATA: gt_numbers TYPE TABLE OF i.
DO 5 TIMES.
APPEND sy-index TO gt_numbers.
ENDDO.
Modern ABAP 7.40+ FOR Expression:
DATA(gt_numbers) = VALUE itab_i_type( FOR i = 1 UNTIL i > 5 ( i ) ).
Both constructs produce identical internal table contents, but the modern FOR expression is concise and functional.
Comparison Matrix: DO vs. WHILE vs. LOOP AT vs. FOR
| Loop Type | Iteration Condition | Primary Use Case | System Variable Tracked |
|---|---|---|---|
DO n TIMES | Fixed integer count n or unconditional DO. | Repeat logic fixed times or till manual EXIT. | sy-index |
WHILE cond | Evaluates boolean expression cond before each run. | Repeat as long as condition evaluates to true. | sy-index |
LOOP AT itab | Sequential iteration over internal table rows. | Processing collection records line-by-line. | sy-tabix |
FOR i = ... | Modern 7.40+ constructor loop inline expression. | Building tables or array transformations. | Iterator variable i |
Self-Assessment Checkpoint
💡 **What is the initial value of SY-INDEX when a DO loop starts executing?**
The system variable SY-INDEX starts at 1 on the first iteration of the loop, not 0. It increments by 1 with each consecutive pass.
💡 **What happens if you define a DO statement without specifying the TIMES parameter?**
A DO statement without TIMES creates an Infinite Loop. It will run forever unless it encounters an EXIT or REJECT statement inside the loop body to terminate execution.
Common Errors & Best Practices
- Guard Against Infinite Loops: When writing
DO.withoutTIMES, place your exit condition check near the top of the loop block to avoid unnecessary execution steps. - Cache SY-INDEX in Nested Loops:
SY-INDEXgets overwritten in nested loops. Store the outer loop’sSY-INDEXin a dedicated local variable before stepping into the inner loop. - Avoid Hardcoded Loop Limits: Instead of writing
DO 100 TIMES, bind your iteration limit to explicit constants or calculated variables (e.g.DO lv_count TIMES). - Prefer LOOP AT for Internal Tables: Avoid using
DOloops withREAD TABLE ... INDEX sy-indexto process internal tables.LOOP AT itabis significantly faster and cleaner.
Summary
The DO loop is a foundational control structure in SAP ABAP programming. Whether generating sequential record IDs, performing mathematical iterations, or parsing string data, understanding DO ... ENDDO, SY-INDEX, and control statements (EXIT, CONTINUE, CHECK) enables you to write clean, predictable application code.
Written by Daksh Dedha
SAP Technical ConsultantDaksh is an SAP Technical Consultant specializing in ABAP programming, SAP S/4HANA migrations, Fiori development, and BTP cloud architecture. He authors free, hands-on tutorials to make enterprise SAP education accessible to all developers.
Test Your Knowledge
Loading question...
Quiz Completed
Related Tutorials
SAP ABAP Enhancement Framework — User Exits, BADIs, and Enhancement Points
Master SAP ABAP enhancements. Learn User Exits, Customer Exits, BADIs, Enhancement Points, and Implicit/Explicit Enhancement Spots to modify standard SAP without modifying source code.
ABAP ProgrammingABAP CDS Views — Core Data Services Complete Guide for Beginners
Learn ABAP CDS Views from scratch. Understand how to create CDS views in Eclipse ADT, use annotations, associations, parameters, and build OData services with CDS.
ABAP ProgrammingMessage Handling in SAP ABAP — Complete SE91 Message Classes Guide
Master SAP ABAP message handling. Learn how to create message classes in transaction SE91, use the MESSAGE statement, handle error types A E W I S X, and pass placeholders.
Found this tutorial useful? Share it with your SAP development team.