Sum of all elements in 1D and 2D array in Python

        This program adds the elements from beginning to end. It can be done by built-in functions or using loop.

Let us discuss many methods as follows…

1D array elements:

The methods are

  • ·       Using built-in method sum ()
  • ·       Using loops
  • ·       Using numpy

Using built-in method sum ():

#create an array of elements

n_array = [100, 200, 300, 400, 500]

#find the total from the sum()

a_total = sum(n_array)

#print the sum

print("Sum of the elements in the array:", a_total)

Output:

Sum of the elements in the array: 1500

Using loops:

#Array creation

n_array = [11, 22, 33, 44, 55]

a_total = 0

#using a for loop to find the sum

for no in n_array:

    a_total += no

#Print the sum

print("Sum of the elements are:", a_total)

Output:

Sum of the elements are: 165

Using Numpy:

              This uses Numpy built-in method.

#create object for numpy

import numpy as np1

#Create an array ,find the total and print the sum

n_array = np1.array([11, 22, 30, 44, 56])

a_total = np1.sum(n_array)

print("Sum of elements:", a_total)

Output:

Sum of elements: 163

Next, 2D arrays.

2D array elements:

              2D array has set of rows and columns. Here, we use nested loops and numpy to find the sum of the elements.

Using nested loops:

#create a 2D array

s_matrix = [

    [11, 2, 31],

    [40, 15, 16],

    [71, 80, 9]

]

#using nested for loop to find the sum

m_total = 0

for m_row in s_matrix:

    for m_element in m_row:

        m_total += m_element

#Print the output.

print("Sum of all the elements are:", m_total)

Output:

Sum of all the elements are: 275

Using numpy:

#create an object for numpy

import numpy as np1

#2D matrix creation

s_matrix = np1.array([

    [10, 20, 30],

    [40, 50, 60],

    [70, 80, 90]

])

#find the sum of all elements

s_total = np1.sum(s_matrix)

#final display

print("Sum of all the elements are:", s_total)

Output:

Sum of all the elements are: 450

That’s all. The sum of all the elements in 1D and 2D array was done successfully in different methods. Keep coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Datatypes and Variables in java script