C++ Online Compiler
Example: MatrixRowColumnSum in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// MatrixRowColumnSum #include <iostream> #include <vector> // Using vector for dynamic arrays, or fixed-size array can be used using namespace std; int main() { // Step 1: Define the matrix dimensions and elements const int ROWS = 3; const int COLS = 4; // Initialize a 2D array (matrix) int matrix[ROWS][COLS] = { {10, 20, 15, 30}, {5, 25, 35, 40}, {12, 18, 22, 28} }; cout << "Original Matrix:" << endl; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { cout << matrix[i][j] << "\t"; } cout << endl; } cout << endl; // Step 2: Calculate and display sum of each row cout << "Row Sums:" << endl; for (int i = 0; i < ROWS; ++i) { // Loop through each row int rowSum = 0; // Initialize sum for the current row for (int j = 0; j < COLS; ++j) { // Loop through each element in the current row rowSum += matrix[i][j]; } cout << "Sum of Row " << i + 1 << ": " << rowSum << endl; } cout << endl; // Step 3: Calculate and display sum of each column cout << "Column Sums:" << endl; for (int j = 0; j < COLS; ++j) { // Loop through each column int colSum = 0; // Initialize sum for the current column for (int i = 0; i < ROWS; ++i) { // Loop through each element in the current column colSum += matrix[i][j]; } cout << "Sum of Column " << j + 1 << ": " << colSum << endl; } return 0; }
Output
Clear
ADVERTISEMENTS