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

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

Shell Script: Simple Array Element Summation

Shell (sh)

Goal -- WPM

Ready
Exercise Algorithm Area
1#!/bin/sh
2
3# Function to calculate the sum of numeric elements in a shell array.
4# Arguments:
5# $1: The array variable name (passed indirectly).
6# This function iterates through the provided array and sums up its numeric elements.
7# Non-numeric elements are ignored with a warning.
8
9sum_array_elements() {
10local array_name="$1"
11local sum=0
12local element_count=0
13
14# Check if the array is empty.
15# We need to indirect the array name to get its elements.
16# Using 'eval' is generally discouraged due to security risks, but for
17# controlled internal scripts and simple cases like this, it can be used.
18# A safer alternative would be to pass elements as separate arguments or use namerefs (bash 4.3+).
19# For POSIX sh compatibility, 'eval' or passing elements individually is common.
20
21# Let's use a method that avoids 'eval' by passing elements as arguments.
22# The caller will expand the array into arguments.
23
24# This function expects elements to be passed as individual arguments.
25# The caller should expand the array like: sum_array_elements "${my_array[@]}"
26
27# Iterate through each element passed as an argument.
28for element in "$@"; do
29element_count=$((element_count + 1))
30
31# Check if the element is a valid integer.
32# This regex checks for optional sign and digits.
33if [[ "$element" =~ ^-?[0-9]+$ ]]; then
34sum=$((sum + element))
35else
36# Handle non-numeric elements by warning and skipping.
37echo "Warning: Skipping non-numeric element '$element'." >&2
38fi
39done
40
41# Handle the edge case of an empty array (no elements passed).
42if [ "$element_count" -eq 0 ]; then
43echo "The array is empty. Sum is 0."
44return 0 # Indicate success, sum is 0
45fi
46
47echo "Sum of numeric elements: $sum"
48return 0 # Indicate success
49}
50
51# --- Main execution block
52
53# Example Usage:
54
55# Test case 1: Array with positive integers.
56echo "--- Test Case 1: Positive Integers ---"
57my_numbers_1=(
5810
5920
6030
6140
6250
63)
64sum_array_elements "${my_numbers_1[@]}"
65
66# Test case 2: Array with positive and negative integers.
67echo "\n--- Test Case 2: Mixed Integers ---"
68my_numbers_2=(
6915
70-5
7125
72-10
735
74)
75sum_array_elements "${my_numbers_2[@]}"
76
77# Test case 3: Array with non-numeric elements.
78echo "\n--- Test Case 3: Non-Numeric Elements ---"
79my_mixed_array=(
80100
81"hello"
82200
83"world"
84300
85"10"
86)
87sum_array_elements "${my_mixed_array[@]}"
88
89# Test case 4: Empty array.
90echo "\n--- Test Case 4: Empty Array ---"
91empty_array=()
92sum_array_elements "${empty_array[@]}"
93
94# Test case 5: Array with only non-numeric elements.
95echo "\n--- Test Case 5: Only Non-Numeric Elements ---"
96non_numeric_array=(
97"apple"
98"banana"
99"cherry"
100)
101sum_array_elements "${non_numeric_array[@]}"
102
103# Test case 6: Array with zero.
104echo "\n--- Test Case 6: Array with Zero ---"
105array_with_zero=(
10610
1070
10820
109)
110sum_array_elements "${array_with_zero[@]}"
111
112exit 0
Algorithm description viewbox

Shell Script: Simple Array Element Summation

Algorithm description:

This shell script defines a function `sum_array_elements` that calculates the sum of numeric elements within a given array. It iterates through the array elements, checks if each element is a valid integer using a regular expression, and accumulates the sum. Non-numeric elements are identified and skipped with a warning message. This is a fundamental programming task useful for data processing and basic calculations within shell scripts, such as aggregating numerical data from configuration files or command-line arguments.

Algorithm explanation:

The `sum_array_elements` function takes an array's elements as separate arguments. It initializes a `sum` variable to 0 and `element_count` to track the number of elements processed. It iterates through each provided argument (`element`). Inside the loop, it uses a regular expression `^-?[0-9]+$` to validate if the `element` is an integer (allowing for an optional leading minus sign). If it's a valid integer, it's added to the `sum` using arithmetic expansion `$((...))`. If not, a warning is printed to standard error, and the element is skipped. After the loop, it checks if `element_count` is zero, indicating an empty array, and prints a specific message. Finally, it prints the calculated sum. The time complexity is O(N * R), where N is the number of elements in the array and R is the time complexity of the regex check (typically very fast for this simple pattern). The space complexity is O(1) as it only uses a few variables to store the sum and count.

Pseudocode:

function sum_array_elements(elements...):
  initialize sum = 0
  initialize element_count = 0

  for each element in elements:
    increment element_count
    if element matches regex "^-?[0-9]+$":
      add element to sum
    else:
      print warning "Skipping non-numeric element 'element'" to stderr

  if element_count is 0:
    print "The array is empty. Sum is 0."
  else:
    print "Sum of numeric elements: " + sum

  return success