**REDUCE OPERATOR IN ABAP**

Used to calculate total and subtotals.

__Syntax: __

REDUCE <type>( INIT ... FOR... THEN... UNTIL... NEXT... )

INIT - Initial value

FOR - Initialize iteration

THEN - Increment value

UNTIL - Iteration End condition

NEXT - Operation

How To Use REDUCE Operator in ABAP 7.4/7.5 New Syntax

__Example 1__

To find the sum of first 10 numbers. sum of first 10 numbers.

DATA(v1) = REDUCE i( INIT sum = 0 FOR i = 1 THEN i + 1 UNTIL i > 10 NEXT sum = sum + i ).

Even if THEN keyword is not specified the default increment will happen with 1

DATA(v1) = REDUCE i( INIT sum = 0 FOR i = 1 UNTIL i > 10 NEXT sum = sum + i ). WRITE:/ v1.

Example 2 :

**Using String**

DATA(v2) = REDUCE string( INIT text = `Count up:` FOR i = 1 THEN i + 1 UNTIL i > 10 NEXT text = text && | { i } | ). DATA(v3) = REDUCE string( INIT text = `Count down:` FOR i = 10 THEN i - 1 UNTIL i < 1 NEXT text = text && | { i } | ). WRITE:/ v2. WRITE:/ v3.

__Output:__

Count up: 1 2 3 4 5 6 7 8 9 10

Count down: 10 9 8 7 6 5 4 3 2 1

__Example 3__

**Calculate Sum in internal table**

__Code:__

REPORT ztest_program. TYPES: BEGIN OF ty_emp, empname TYPE string, role TYPE string, salary TYPE i, END OF ty_emp. DATA: it_employees TYPE TABLE OF ty_emp. DATA: lv_tot_salary TYPE i. *-- Populate Internal Table it_employees = VALUE #( ( empname = 'John' role = 'Analyst' salary = '10000' ) ( empname = 'Steve' role = 'Sr Analyst' salary = '15000' ) ( empname = 'Marcus' role = 'Jr Analyst' salary = '7000' ) ( empname = 'Surya' role = 'Jr Analyst' salary = '7000' ) ). *-- TOTAL CALCULATION *--- Before ABAP 7.4/7.5 *LOOP AT it_employees INTO DATA(wa_employees). * * lv_tot_salary = lv_tot_salary + wa_employees-salary. *ENDLOOP. *--- After ABAP 7.4/7.5 lv_tot_salary = REDUCE i( INIT total = 0 FOR wa_employees IN it_employees NEXT total = total + wa_employees-salary ). WRITE:/ 'Total Salary:', lv_tot_salary.

__Output:__

Total Salary:39000

The work area is local to the reduce expression and declaration is not required.

If the requirement is to find the sum with particular condition. lets say role = 'Jr Analyst' then insert WHERE condition.

lv_tot_salary = REDUCE i( INIT total = 0 FOR wa_employees IN it_employees WHERE ( role = = 'Jr Analyst' ) NEXT total = total + wa_employees-salary ).

**REDUCE in Nested loops**

Read this: https://blogs.sap.com/2017/05/25/replace-the-loop-for-reduce-operator/