# Sum of all elements of an array

by

Jiffin Joachim Gomez on 24th February 2017

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.

Typecode | Description |

b | Represents signed integer of size 1 byte |

B | Represents unsigned integer of size 1 byte |

c | Represents character of size 1 byte |

u | Represents unicode character of size 2 bytes |

h | Represents signed integer of size 2 bytes |

H | Represents unsigned integer of size 2 bytes/td> |

i | Represents signed integer of size 2 bytes |

I | Represents unsigned integer of size 2 bytes |

w | Represents Unicode character of size 4 bytes |

l | Represents signed integer of size 4 bytes |

L | Represents unsigned integer of size 4 bytes |

f | Represents floating point of size 4 bytes |

d | Represents 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

## Comments