Home »
C++ Programs
C++ program to find the sum of each column of matrix using class
Submitted by Shubh Pachori, on October 09, 2022
Problem statement
Given a matrix, we to find the sum of each column of matrix using the class and object approach.
Example:
Input:
Enter Matrix elements :
[0][0]: 1
[1][1]: 2
[2][2]: 3
[0][0]: 4
[1][1]: 5
[2][2]: 6
[0][0]: 7
[1][1]: 8
[2][2]: 9
Output:
Entered Matrix :
1 2 3
4 5 6
7 8 9
Sum of 0 column is 12
Sum of 1 column is 15
Sum of 2 column is 18
C++ code to find the sum of each column 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 functions
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 << "[" << column << "][" << column << "]:";
cin >> matrix[row][column];
}
}
}
// sumColumn() function to add elements
// of each column
void sumColumn() {
// initialising int type variables
// to perform operations
int row, column, sumcolumn;
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
// columns elements of the matrix
for (row = 0; row < 3; row++) {
sumcolumn = 0;
for (column = 0; column < 3; column++) {
sumcolumn = sumcolumn + matrix[column][row];
}
cout << "Sum of " << row << " column is " << sumcolumn << endl;
}
}
};
int main() {
// create an object
Matrix M;
// calling getMatrix() function to
// insert Matrix
M.getMatrix();
// calling sumColumn() function to add each column
M.sumColumn();
return 0;
}
Output
Enter Matrix elements :
[0][0]:2
[1][1]:4
[2][2]:6
[0][0]:8
[1][1]:9
[2][2]:7
[0][0]:5
[1][1]:4
[2][2]:2
Entered Matrix :
2 4 6
8 9 7
5 4 2
Sum of 0 column is 15
Sum of 1 column is 17
Sum of 2 column 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 sumColumn() to store the matrix elements and to find the sum of each column of the matrix.
In the main() function, we create an object M of class Matrix, reading the inputted matrix by the user using getMatrix() function, and finally call the sumColumn() member function to find the sum of each column of the matrix. The sumColumn() function contains the logic to find the sum of each column of the matrix and printing the result.
C++ Class and Object Programs (Set 2) »