Press "Enter" to skip to content

Python program to find sum of array

In this post, we will discuss how to find the sum of an array in python.

Sum of an array means adding each element that is present in the array.

Consider examples:

Input : array[] = {10 ,20 ,30 ,40 ,50}
Output: 10 + 20 + 30 + 40 + 50 = 150 
Freshers Placement

As we saw the examples. Let’s have look at the programs now.

There are two ways of finding the sum

  1. Use in-built sum() function given by python
  2. Iterate through the array and add elements

Program 1: Find sum using in-built function

# python code to find
# the sum of each element
# using in-built function

#declare the array
my_array = [20, 40, 60, 90]

# call the function to get the sum
result = sum(my_array)
  
# print result
print ('Sum of the array using in-built function is:',result)

Output

Sum of the array using in-built function is: 210

Steps:

  1. Declare and initialize the array
  2. Call in-built sum(my_array) function to get the result

Let’s look at another example now.

Program 2: Iterate through the array and add elements

# python code to find 
# the sum of elements in an array

# method that iterates
# through each element and
# adds them
def find_sum(my_array):
    
    # variable that stores
    # the sum of an array
    sum=0
      
    # iterate each element
    # and add to the sum
    # you can use any other loop
    # but we are using for loop
    for i in my_array:
        sum = sum + i
          
    return(sum) 
    
input_array=[5, 10, 15, 20] 
  
result = find_sum(input_array)

# print the value of sum 
print ('Sum is :', result)

Output

Sum is : 50
Freshers Placement

Steps

  1. Write a method find_sum(), that accepts the array, iterates through its elements, and sum it
  2. Declare and initialize the array
  3. Call find_sum() and get back the result
  4. Print the sum

Comments are closed.