Python program that uses a for loop to print the sum of all elements in an array
def sum_elements(arr):
total = 0
for i in arr:
total += i
return total
# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(sum_elements(arr))
The function sum_elements(arr)
takes an array as an argument. It uses a for loop to iterate over the elements of the array and a variable total
to keep track of the sum of the elements. For each element, it adds the element to the total
variable. Finally, it returns the total
variable which is the sum of all the elements in the array.
The example usage creates an array and calls the sum_elements()
function to find the sum of all elements in the array, and then it prints the sum.
You could also use the sum()
function to find the sum of all elements in an array
def sum_elements(arr):
return sum(arr)
This method uses the sum()
function to find the sum of all elements in the array and returns it.