Home »
C++ Programs
C++ program to find the sum of each row of matrix using class
Submitted by Shubh Pachori, on September 17, 2022
Problem statement
Given a matrix, we have to find the sum of each row of matrix using the class and object approach.
Example:
Input:
Enter Matrix elements :
[0][0]: 8
[0][1]: 4
[0][2]: 3
[1][0]: 5
[1][1]: 8
[1][2]: 0
[2][0]: 9
[2][1]: 6
[2][2]: 1
Output:
Entered Matrix :
8 4 3
5 8 0
9 6 1
Sum of 0 row is 15
Sum of 1 row is 13
Sum of 2 row is 16
C++ code to find the sum of each row of matrix using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Matrix {
// private data member
private:
int matrix[3][3];
// public member funtions
public:
// getMatrix() funtion to insert matrices
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];
}
}
}
// sumRow() funtion to add elements
// of each row
void sumRow() {
// initialising int type variables
// to perform operations
int row, column, sumrow;
cout << "\nEntered Matrix :" << endl;
// for loop to show the inserted 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 add each rows elements of the matrix
for (row = 0; row < 3; row++) {
sumrow = 0;
for (column = 0; column < 3; column++) {
sumrow = sumrow + matrix[row][column];
}
cout << "Sum of " << row << " row is " << sumrow << endl;
}
}
};
int main() {
// create an object
Matrix M;
// calling getMatrix() funtion to
// insert Matrix
M.getMatrix();
// calling sumRow() funtion to
// add each row
M.sumRow();
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 0 row is 6
Sum of 1 row is 15
Sum of 2 row is 24
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 sumRow() to store the matrix elements and to find the sum of each row of the 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 sumRow() member function to find the sum of each row of the matrix. The sumRow() function contains the logic to find the sum of each row of the matrix and printing the result.
C++ Class and Object Programs (Set 2) »