ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

ABAP Simple Array Summation

ABAP

Goal -- WPM

Ready
Exercise Algorithm Area
1FUNCTION zcl_array_utils=>sum_array.
2" Calculates the sum of all elements in an integer array.
3" Handles empty arrays by returning 0.
4
5DATA: lt_numbers TYPE STANDARD TABLE OF i.
6" Example input: lt_numbers = VALUE #( ( 1 ) ( 2 ) ( 3 ) ).
7" Example input: lt_numbers = VALUE #( ). " Empty array
8
9DATA(lv_total_sum) = zcl_array_utils=>calculate_sum( lt_numbers ).
10
11" lv_total_sum now holds the sum.
12
13ENDFUNCTION.
14
15
16FUNCTION zcl_array_utils=>calculate_sum.
17" Helper function to perform the summation.
18
19PARAMETERS:
20it_numbers TYPE STANDARD TABLE OF i.
21
22" Initialize sum to zero.
23DATA lv_sum TYPE i VALUE 0.
24
25" Check for empty array edge case.
26IF it_numbers IS INITIAL.
27RETURN lv_sum.
28ENDIF.
29
30" Iterate through the array and add each element to the sum.
31LOOP AT it_numbers INTO DATA(lv_number).
32lv_sum = lv_sum + lv_number.
33ENDLOOP.
34
35RETURN lv_sum.
36
37ENDFUNCTION.
Algorithm description viewbox

ABAP Simple Array Summation

Algorithm description:

This ABAP program calculates the sum of all integer elements within an array. It defines a main function that calls a helper function to perform the actual summation. The helper function iterates through the array, accumulating the sum of its elements. It also includes a check for an empty array, returning zero in such cases. This is a fundamental operation used in data analysis, financial calculations, and basic data aggregation tasks.

Algorithm explanation:

The algorithm initializes a sum variable to zero. It then iterates through each element of the input array using a `LOOP AT` statement. In each iteration, the current element's value is added to the sum variable. The time complexity is O(N), where N is the number of elements in the array, because each element is visited exactly once. The space complexity is O(1) as it only uses a constant amount of extra space for the sum variable and loop work area. The algorithm correctly handles the edge case of an empty array by returning zero, ensuring robustness.

Pseudocode:

FUNCTION calculate_sum(array_of_integers):
  sum = 0
  IF array_of_integers is empty:
    RETURN 0

  FOR EACH number in array_of_integers:
    sum = sum + number

  RETURN sum