Python Program to Print Sum of all Elements in an Array
Python program to print sum of all elements in an array
A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep objects of the same type together. In this example, we'll look at a Python program that prints the sum of all the elements in an array. We can get the sum of all array elements in several ways, and some of them are given as follows:
- Traverse/access each element, add the elements in a variable sum and then print the sum.
- Using the sum() function to get the sum of array elements.
Example: Given array = [4, 8, 2] Output: 4+8+2 = 14
Source Code
The following source code uses the "for loop" that traverses/access each element and adds them in a variable sum and then prints the sum.
#Python program to find the sum of all elements in an array #Initialize an array arr1 = [2, 7, 8, 9, 10, 22, 25] #Initialize the variable to store the sum sum = 0 #Iterates through an array to add each element of an array for i in range(0, len(arr1)): sum = sum + arr1[i] print ("Sum of the array is ", sum)
Output

Explanation: In this program, we have first initialized and declare an array. Also, we have declared a temporary variable and initialized its value to 0. Next, we will use the FOR loop to iterate the array elements from 0 to the array length. After each iteration, the sum's value will be increased by the ith element of an array, and when the iterations are completed, the final result will be printed.
The following source code uses the inbuilt function sum() to find the sum of all the elements of an array and their results on the screen:
#Python program to find the sum of all elements in an array #Initialize an array arr1 = [2, 7, 8, 9, 10, 22, 25] #sum() function will return the value after adding all the elements result = sum(arr1) #Print the result print("The sum of an array is ", result)
Output
