(Sum the major diagonal in a matrix) Write a function that sums all the numbers of the major diagonal in an n x n matrix of integers using the following header:
def sumMajorDiagonal(m):
The major diagonal is the diagonal that runs from the top left corner to the bottom right corner in the square matrix. Write a test program that reads a 4 x 4 matrix and displays the sum of all its elements on the major diagonal. Here is a sample run:
Enter a 4-by-4 matrix row for row 1: 1 2 3 4
Enter a 4-by-4 matrix row for row 2: 5 6.5 7 8
Enter a 4-by-4 matrix row for row 3: 9 10 11 12
Enter a 4-by-4 matrix row for row 4: 13 14 15 16
Sum of the elements in the major diagonal is 34.5
Sum the major diagonal in a matrix Program Code:
# Function to calculate the sum of numbers on the major diagonal of a matrix
def sumMajorDiagonal(m):
diagonalSum = 0
n = len(m) # Get the size of the matrix (assuming it's square)
for i in range(n):
diagonalSum += m[i][i] # Add the value on the diagonal at position (i, i) to the sum
return diagonalSum
# Test program
def main():
matrix = [] # Initialize an empty matrix
# Prompt the user to enter a 4x4 matrix
for i in range(4):
row = input(f"Enter a 4-by-4 matrix row for row {i + 1}: ").split()
row = [float(num) for num in row] # Convert the input numbers to floats
matrix.append(row)
# Calculate the sum of numbers on the major diagonal
diagonalSum = sumMajorDiagonal(matrix)
# Display the sum of the major diagonal
print(f"Sum of the elements in the major diagonal is {diagonalSum}")
# Call the test program
main()
Executed Output:
Enter a 4-by-4 matrix row for row 1: 1 2 3 4
Enter a 4-by-4 matrix row for row 2: 5 6.5 7 8
Enter a 4-by-4 matrix row for row 3: 9 10 11 12
Enter a 4-by-4 matrix row for row 4: 13 14 15 16
Sum of the elements in the major diagonal is 34.5