Python Program to find sum of array elements using for
Program
number_array = list()
total = 0
size = int(input("Enter the size of array:\t"))
print("Enter the numbers in array: ")
for i in range(int(size)):
n = input()
number_array.append(int(n))
for element in number_array:
total = total+element
print("Sum of array is:\t", total)
This program calculates the sum of all elements in an array using a for
loop.
-
User Input for Array Size
- The user enters the number of elements they want in the array.
-
Array Input
- A loop runs
size
times, taking user input and storing it innumber_array
.
- A loop runs
-
Summation Using
for
Loop- The
for
loop iterates over each element innumber_array
, adding its value tototal
.
- The
-
Display the Sum
- The final sum of all array elements is printed.
Key Takeaways
- Uses loops to take input and process the array.
- Uses a for loop to iterate over array elements for summation.
- Stores the sum in the
total
variable and prints the result.
Output
$ python3 sum_of_array_elements_using_for.py
Enter the size of array: 4
Enter the numbers in array:
45
67
89
37
Sum of array is: 238