In: Computer Science
Write a Python program which adds up columns and rows of given table as shown in the specified figure. Example test case (the four lines below “Input cell value” are input from user, and the five lines below “Results:” are the output of the program.):
Input number of rows/columns (0 to exit)
4
Input cell value:
25 69 51 26
68 35 29 54
54 57 45 63
61 68 47 59
Result:
25 69 51 26 171
68 35 29 54 186
54 57 45 63 219
61 68 47 59 235
208 229 172 202 811
Input number of rows/columns (0 to exit)
Here, int the code , we have declared an double dimenstional array matrix startingly assigned 0 to each value .
We have used two loop for i and j index to input values from console
In length variable , we have stored rows/column count
After inputting values , we have again used two loop for i and j index to calculate sum of all rows and columns
Then after that, again loop is used to count sum of last column which is already a sum of all rows
Then we have printed the entered array in console
And , then printed the summed array in console
____________________________________
Please find below code in Python :
length=int(input("Input number of rows/columns: "))
matrix=[[0 for i in range(length+1)] for j in range(length+1)]
for i in range (length):
for j in range (length):
value= int(input("Enter value for row : "))
matrix[i][j]=value
colCount=0
for i in range (length):
sumRow=0
sumCol=0
for j in range (length):
sumRow+= matrix[i][j]
sumCol+= matrix[j][i]
matrix[i][j+1]=sumRow
matrix[length][colCount]=sumCol
colCount+=1
sumLastCol=0
for i in range(length):
sumLastCol+=matrix[i][length]
matrix[length][length]=sumLastCol
print("Input cell value: ")
for i in range (length):
for j in range (length):
print(matrix[i][j],end=" ")
print()
print("Result : ")
for i in range (length+1):
for j in range (length+1):
print(matrix[i][j],end=" ")
print()
Please find below OUTPUT screenshot: