Home »
C++ Programs
C++ program to find the sum of both diagonals of matrix using class
Submitted by Shubh Pachori, on October 03, 2022
Problem statement
Given a matrix, we have to find the sum of both diagonals of the matrix using a C++ program with the class and object approach.
Example:
Input:
Enter Matrix elements :
[0][0]:2
[0][1]:4
[0][2]:6
[1][0]:1
[1][1]:3
[1][2]:5
[2][0]:8
[2][1]:7
[2][2]:9
Output:
Entered Matrix :
2 4 6
1 3 5
8 7 9
Sum of Left diagonal is 14
Sum of Right diagonal is 17
C++ code to find the sum of both diagonals of matrix using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Matrix {
// private data members
private:
int matrix[3][3];
// public member functions
public:
// getMatrix() function to insert matrix
void getMatrix() {
cout << "Enter Matrix elements :" << endl;
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
cout << "[" << row << "][" << column << "]: ";
cin >> matrix[row][column];
}
}
}
// sumDiagonal() function to find sum of
// diagonal of matrix
void sumDiagonal() {
// initialising variables to perform operations
int row, column, sumleft = 0, sumright = 0;
cout << "\nEntered Matrix :" << endl;
// nested for loop to show insertted matrix
for (row = 0; row < 3; row++) {
for (column = 0; column < 3; column++) {
cout << matrix[row][column] << " ";
}
cout << "\n";
}
cout << "\n";
// nested for loop to traverse the whole matrix
for (row = 0; row < 3; row++) {
for (column = 0; column < 3; column++) {
// if condition for left diagonal
if (row == column) {
sumleft = sumleft + matrix[row][column];
}
// if condition for right diagonal
if ((row + column) == 2) {
sumright = sumright + matrix[row][column];
}
}
}
cout << "Sum of Left diagonal is " << sumleft << endl;
cout << "Sum of Right diagonal is " << sumright << endl;
}
};
int main() {
// create an object
Matrix M;
// calling getMatrix() function to insert Matrix
M.getMatrix();
// calling sumDiagonal() function to find
// sum of diagonal of Matrix
M.sumDiagonal();
return 0;
}
Output
Enter Matrix elements :
[0][0]: 1
[0][1]: 2
[0][2]: 3
[1][0]: 4
[1][1]: 5
[1][2]: 6
[2][0]: 7
[2][1]: 8
[2][2]: 9
Entered Matrix :
1 2 3
4 5 6
7 8 9
Sum of Left diagonal is 15
Sum of Right diagonal is 15
Explanation
In the above code, we have created a class Matrix, one int type 2d array data members matrix[3][3] to store the elements of the matrix, and public member functions getMatrix() and sumDiagonal() to store the matrix elements and to find the sum of both diagonal of matrix.
In the main() function, we are creating an object M of class Matrix, reading the inputted matrix by the user using getMatrix() function, and finally calling the sumDiagonal() member function to find the sum of both diagonal of matrix. The sumDiagonal() function contains the logic to find the sum of both diagonals of the matrix and printing the result.
C++ Class and Object Programs (Set 2) »