Write a c++ program: (Sum the major diagonal in a matrix) Write a function that
ID: 3766446 • Letter: W
Question
Write a c++ program:
(Sum the major diagonal in a matrix) Write a function that sums all the double values in the major diagonal in an n*n matrix of double values using the following header:
const int SIZE=4;
double sumMajorDiagonal(const double m[][SIZE]);
Write a test program that reads a 4 by 4 matrix and displays the sum of all its elements on the major diagonal. Here is a smaple run:
Enter a 4-by4 matrix row by row:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sum of the elements in the major diagonal is 34.
Additional details:
Prompt user to enter n (the size of the n x n matrix). The program should work for any n >= 2.
Prompt the user to enter the elements in the matrix row-by-row.
Display the sum of the elements in the major diagonal and call a function to find the sum of each column). The sum should be displayed from the main function, not from the function sumMajorDiagonal.
Include a printout of the main program and the function.
Include printouts for the test case in the aabove as well as for a 2x2 matrix and a 3x3 matrix
Explanation / Answer
You are asking for some specific size. And you are also asking for generalized example in the last line of your question. So, I tried passing an additional parameter n, for the function, using which, the loop will run. Other than that, everything remains the same. If you have any further queries, just get back to me.
Here is the code for you.
#include <stdio.h>
const int SIZE=4;
double sumMajorDiagonal(const double m[][SIZE], int n)
{
double diagonalSum = 0;
for(int i = 0; i < n; i++)
diagonalSum += m[i][i];
return diagonalSum;
}
int main()
{
double A[SIZE][SIZE];
int i, j, n;
printf("Enter the value of n (the size of n x n matrix): ");
scanf("%i", &n);
printf("Enter a %i x %i matrix row-by-row: ", n, n);
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
scanf("%lf", &A[i][j]);
printf("Sum of the elements in the major diagonal is %.2lf. ", sumMajorDiagonal(A, n));
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.