Calculate the Sum of Elements in an Array
Understanding Sum Calculation
Summing elements in an array involves adding all the elements together to get a total sum.
We will explore three different methods to calculate the sum of an array using Python.
Method 1: Using a Loop
This method iterates through the array and accumulates the sum.
def sum_array_loop(arr):
total = 0
for num in arr:
total += num
return total
arr = [1, 2, 3, 4, 5]
print("Sum:", sum_array_loop(arr))
Method 2: Using Recursion
This method calculates the sum recursively.
def sum_recursive(arr, n):
if n == 0:
return 0
return arr[n - 1] + sum_recursive(arr, n - 1)
arr = [1, 2, 3, 4, 5]
print("Sum:", sum_recursive(arr, len(arr)))
Method 3: Using Built-in Function
This method calculates the sum using Python's built-in sum function.
arr = [1, 2, 3, 4, 5]
print("Sum:", sum(arr))