Given an array arr[] of integers of size n. Your task is to write a Python program that calculates and prints the sum of all the elements present in the array.
Example:
Input: [3, 8, 12, 5, 2] Output: The sum of elements is 30 Input: [1, 2, 3, 4, 5] Output: The sum of elements is 15 Input: [-2, 5, 7, -1, 9] Output: The sum of elements is 18
There are multiple ways to find the sum of all array elements and in this article, we will learn few of them.
Approach 1: Sum of Array Elements Using Loop.
One fundamental method to calculate the sum of elements in a Python array involves utilizing a loop structure. This classic approach employs an iterative process to traverse through each element of the array and accumulate the sum.
Algorithm Steps:
- Initialize a variable sum to zero.
- Traverse through each element in the array.
- Add the current element to the running sum.
- After iterating through all elements, return the final sum.
Python Code:
# Python code to find sum of array using loop #Initialize array arr = [2, 4, 6, 8, 1] sum = 0 # Traverse array for num in arr: sum += num #Print the sum value print("Sum of Array Elements: " + str(sum))
Sum of Array Elements: 21
- Time Complexity: This method operates in linear time, with a complexity of O(n), where 'n' represents the number of elements in the array.
- Space Complexity: The space complexity is constant, denoted as O(1), as only a single variable (sum) is used.
Approach 2: Sum of Array Elements Using sum() Function.
An alternative and concise approach to compute the sum of array elements in Python involves utilizing the built-in sum() function. This function inherently performs the summation, simplifying the code and enhancing readability.
Algorithm Steps:
- Directly apply the sum() function to the array.
- The function internally iterates through each element, calculating the sum.
- Return the computed sum of given array.
Python Code:
# Python code to find sum of array using function #Initialize array arr = [2, 4, 6, 8, 3] # sum funtion of python arraySum = sum(arr) #Print the sum value print("Sum of Array Elements: " + str(arraySum))
Output:
Sum of Array Elements: 23- Time Complexity: This approach has a time complexity of O(n), similar to the loop-based method.
- Space Complexity: The space complexity remains O(1) as it returns a single sum value.
There are many other methods to find sum of array in Python but these two are most simpest way to find the sum of array.
Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.
No comments
Post a Comment