Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

( Sum the major diagonal in a matrix ) Write a function that sums all the double

ID: 3604491 • Letter: #

Question

(Sum the major diagonal in a matrix) Write a function that sums all the double values in the major diagonal in an NxN of double values, in according to the following:

• The size of an array cannot be changed based on user input (dynamic memory allocation), so the matrix should be dimensioned to the max size ever expected (10 x 10 perhaps).

• Prompt user to enter N (the size of the N x N matrix). The program should work for any N >= 2. N should not be used anywhere for matrix dimensions. It is only used in for loops to control user input and printing. Note that a 3x3 matrix is really just using the upper corner of the 10x10 matrix.

• Prompt the user to enter the elements in the matrix row-by-row.

• Display the NxN matrix.

• Display the sum of the elements in the major diagonal. 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 textbook as well as for a 2x2 matrix and a 3x3 matrix.

Please show me the steps needed to complete this question. I am stumped on how to complete it. Thanks.

Explanation / Answer

C++ Code:

#include <iostream>

#include <new>
using namespace std;

int main ()
{
int i,n;
int * p;
int sum=0;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == nullptr)
cout << "Error: memory could not be allocated";
else
{
cout << "Enter the numbers: ";
for (n=0; n<i; n++)
{
  
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
{
cout<<p[n]<<" ";
}
for (n=0; n<i; n++)
{
sum+=p[n];
}
cout << " Sum of elements are " <<sum;
  
delete[] p;
}
return 0;
}

Output: