Write a c program Sum the major diagonal in a matrix Write a
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
Solution
#include <iostream>
using namespace std;
const int SIZE=4;
 double sumMajorDiagonal(double m[][SIZE]);
int main()
 {
 int n;
 //double matrix[][];
 double sum=0;
 double matrix[SIZE][SIZE];
 //enter the size of the matrix
 cout << \"Enter the size of the matrix (nxn)\" << endl;
 cin>>n;
 
 //loop to take matrix value row-by-row
 cout<< \"Enter the matrix row by row\"<<endl;
 for(int i=0;i<n;i++){
 for(int j=0;j<n;j++){
 cin>>matrix[i][j];
 }
 }
 sum=sumMajorDiagonal(matrix);
 cout<<\"The sum of major diagonal is \"<<sum;
 return 0;
 }
 // method to calculate the sum of major diagonal and returns the sum to the main function
 double sumMajorDiagonal(double m[][SIZE]){
 double sum=0;
 for(int i=0;i<SIZE;i++){
 for(int j=0;j<SIZE;j++){
 if( i==j )
 sum += m[i][j];
 }
 }
 return sum;
 }
----------------------output-----------------------------
 Enter the size of the matrix (nxn)
 2   
 Enter the matrix row by row   
 1   
 2   
 3   
 4   
 The sum of major diagonal is 5
---------------------
 Enter the size of the matrix (nxn)
 3   
 Enter the matrix row by row   
 1   
 2   
 3   
 4   
 5   
 6   
 7   
 8   
 9   
 The sum of major diagonal is 15
 --------------------------------
 Enter the size of the matrix (nxn)
 4   
 Enter the matrix row by row   
 1   
 2   
 3   
 4   
 5   
 6   
 7   
 8   
 9   
 10
 11
 12
 13
 14
 15
 16
 The sum of major diagonal is 34
Note:
 Please feel free to ask question. God bless you!



