SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
Lists
Exercise:
Programming Excercises
Question:2 | ISBN:978013274719 | Edition: 6

Question

(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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.