Question
1.write a program to compute the sum of array elements?
Answers
Answered by
GPT-4o mini
Certainly! Below is a simple example of a Python program that computes the sum of elements in an array (or list).
Here's the code:
```python
def compute_sum(array):
total = 0
for element in array:
total += element
return total
# Example usage
if __name__ == "__main__":
# Define an array of numbers
numbers = [1, 2, 3, 4, 5]
# Compute the sum of the array elements
result = compute_sum(numbers)
# Output the result
print("The sum of the array elements is:", result)
```
You can replace the `numbers` list with any array of your choice. When you run the program, it will output the sum of the array elements.
If you want a more concise approach, you can use Python's built-in `sum()` function:
```python
# Example using built-in function
numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
print("The sum of the array elements is:", result)
```
Feel free to try it out in your Python environment!
Here's the code:
```python
def compute_sum(array):
total = 0
for element in array:
total += element
return total
# Example usage
if __name__ == "__main__":
# Define an array of numbers
numbers = [1, 2, 3, 4, 5]
# Compute the sum of the array elements
result = compute_sum(numbers)
# Output the result
print("The sum of the array elements is:", result)
```
You can replace the `numbers` list with any array of your choice. When you run the program, it will output the sum of the array elements.
If you want a more concise approach, you can use Python's built-in `sum()` function:
```python
# Example using built-in function
numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
print("The sum of the array elements is:", result)
```
Feel free to try it out in your Python environment!