Sum of all elements of an array

To use arrays in Python language, you need to import the standard array module. This is because array is not a fundamental data type like strings, integer etc. we import array module in Python like:

from array import *

Once you have imported the array module, you can declare an array. Here is how you do it:

arrayIdentifierName = array(typecode, [Intializers])

Typecodes are the codes that are used to define the type of array values or the type of array. Here is the list of available typecodes.

TypecodeDescription
bRepresents signed integer of size 1 byte
BRepresents unsigned integer of size 1 byte
cRepresents character of size 1 byte
uRepresents unicode character of size 2 bytes
hRepresents signed integer of size 2 bytes
HRepresents unsigned integer of size 2 bytes/td>
iRepresents signed integer of size 2 bytes
IRepresents unsigned integer of size 2 bytes
wRepresents Unicode character of size 4 bytes
lRepresents signed integer of size 4 bytes
LRepresents unsigned integer of size 4 bytes
fRepresents floating point of size 4 bytes
dRepresents floating point of size 8 bytes

In this program we import the array module, then promts the user to input the elements of the array.The user must input the elements with each element separated by a whitespace. The input string is split into a list, typecasted to integer and then assigned to a array variable. To calculates the sum of the elements the array is iterated in a For Loop and added to the sum variable.

Program to print the sum of array elements


# Python program to find the sum of all elements of an array
# importing the standard array module

from array import *

#Read user input
input_str = input("Input all array elements seperated by space character: ")

#creating a new array
new_array = array('i',[ int(i) for i in input_str.split()] )

#intailizing the sum variable
s = 0

#calculating the sum of array elements
for i in new_array:
    s = s + i
print("The sum of all elements of the array is: ",s)

Program Output

Input all array elements seperated by space character: 10 2 5 16 4
The sum of all elements of the array is:  37
>>> 


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.