Python program to print the sum of all elements in an array

python tutorials and learn python

Created with Sketch.

Python program to print the sum of all elements in an array

In this program, we need to calculate the sum of all the elements of an array. This can be solved by looping through the array and add the value of the element in each iteration to variable sum.

 

Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.

ALGORITHM:

  • STEP 1: Declare and initialize an array.
  • STEP 2: The variable sum will be used to calculate the sum of the elements. Initialize it to 0.
  • STEP 3: Loop through the array and add each element of the array to the variable sum as sum = sum + arr[i].

PROGRAM:

  1. #Initialize array   
  2. arr = [12345];
  3. sum = 0;
  4. #Loop through the array to calculate sum of elements  
  5. for i in range(0, len(arr)):
  6.    sum = sum + arr[i];
  7. print(“Sum of all the elements of an array: “ + str(sum));

Output:

Sum of all the elements of an array: 15

Leave a Reply

Your email address will not be published. Required fields are marked *