Reputation: 53
new to programming and Python, using Python 3.x, I have to create a function that adds all the elements in a 2D array, the function should return the addition of all the elements of an array. I have to use 2 for loops to traverse the array and add up all the elements and I can't use any summing functions.
This is what I have so far but it is not functional
def add2D(array):
for row in array:
for entry in row:
print(entry, end=' ')
print()
sum = 0
for row in array (len(input)):
for col in array(len(input[0])-1):
sum = sum + input[row][col]
return sum
Can anyone tell me what I'm doing wrong.
Upvotes: 1
Views: 719
Reputation: 1290
You almost had it. Here's a working version
def add2D(array):
for row in array:
for entry in row:
print(entry, end=' ')
print()
sum = 0
for row in array:
for col in row:
sum = sum + col
return sum
Upvotes: 0
Reputation: 11134
Avoid using range where possible. Below one should work. First iterate over every innerList and then traverse every element of the innerList and add them with your sum
variable.
def add2D(array):
sum=0
for row in array:
for num in row:
sum+=num
return sum
Upvotes: 1