177k views
0 votes
Programming Exercise 8.2 on page 327. Additional details: The size of an array cannot be changed based on user input (dynamic memory allocation), so the matrix should be dimensionsed 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.

User Pcbabu
by
6.1k points

1 Answer

3 votes

Answer:

#include<iostream>

using namespace std;

double sumMajorDiagonal(double n,double sum);

int main()

{

int N;

double a[10][10],n,sum=0; //declare and define matrix of size 10x10

cout<<"Enter the size of the matrix: ";

cin>>N; //input the size of the matrix

if(N<2) //check condition wheather size of the matrix is greater than or equal to 2

{

cout<<"Size of matrix must be 2 or more!"<<"\\";

return 0;

}

for(int i=0;i<N;i++) //loop for Row

{

for(int j=0;j<N;j++) //loop for column

{

cout<<"Enter element: ";

cin>>n; //input the element in matrix

a[i][j] = n;

if(i==j) //check for major diagonal condition

{

sum = sumMajorDiagonal(a[i][j],sum); //call sunMajorDiagonal funtion if condition statisfied

}

}

}

for(int i=0;i<N;i++) //loop for row

{

for(int j=0;j<N;j++) //loop for column

{

cout<<a[i][j]<<" "; //print elements of matrix

}

cout<<"\\"; //next line for new row

}

cout<<"Sum of the elements of major diagonal is: "<<sum<<"\\"; //print sum of the major row calculated

}

double sumMajorDiagonal(double n,double sum)

{

return sum+n; //add the major diagonal elements and return the value

}

Step-by-step explanation:

See attached image for output

Programming Exercise 8.2 on page 327. Additional details: The size of an array cannot-example-1
User Choya
by
5.6k points