Q:

Python program to find the sum of all elements of an array

belongs to collection: Python Array Programs

0

Finding the sum of array elements

There are two ways to find the sum of all array elements1) traverse/access each element and add the elements in a variable sum, and finally, print the sum. And, 2) find the sum of array elements using sum() function.

Example:

    Input: 
    arr = [10, 20, 30, 40, 50]
    Output:
    sum = 150

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python program for sum of the array elements

# Python program for sum of the array elements

# functions to find sum of elements

# Approach 1
def sum_1(arr):
    result = 0
    for x in arr:
        result += x
    return result

# Approach 2
def sum_2(arr):
    result = sum(arr)
    return result

# main function
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    print ('sum_1: {}'.format(sum_1(arr)))
    print ('sum_2: {}'.format(sum_2(arr)))

Output

sum_1: 150
sum_2: 150

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to find a series in an array consis... >>