C++ Online Compiler
Example: Matrix Row and Column Sums Calculation in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Row and Column Sums Calculation #include <iostream> #include <vector> // Required for using std::vector int main() { // Step 1: Define matrix dimensions const int M = 3; // Number of rows const int N = 3; // Number of columns // Step 2: Initialize the matrix (using a 2D vector for flexibility) std::vector<std::vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Step 3: Initialize vectors to store row and column sums // 'rowSums' will have M elements, initialized to 0 std::vector<int> rowSums(M, 0); // 'colSums' will have N elements, initialized to 0 std::vector<int> colSums(N, 0); // Step 4: Calculate row and column sums by iterating through the matrix for (int i = 0; i < M; ++i) { // Outer loop iterates through each row for (int j = 0; j < N; ++j) { // Inner loop iterates through each column in the current row rowSums[i] += matrix[i][j]; // Add current element to the sum of its row colSums[j] += matrix[i][j]; // Add current element to the sum of its column } } // Step 5: Display row sums std::cout << "Row Sums:" << std::endl; for (int i = 0; i < M; ++i) { std::cout << "Row " << i << ": " << rowSums[i] << std::endl; } // Step 6: Display column sums std::cout << "\nColumn Sums:" << std::endl; for (int j = 0; j < N; ++j) { std::cout << "Column " << j << ": " << colSums[j] << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS