Image

Programs - Python - Arrays

Program:

# Initialize array
arr = [1, 2, 3, 4, 5]
total = 0

# Loop through the array to calculate sum of elements
for i in range(0, len(arr)):
total = total + arr[i]

print("Sum of all the elements of an array: ", total)


# Alternative method, with use of built-in sum() method
print("Sum of all the elements of an array:", sum(arr))

Output:

Sum of all the elements of an array: 15