C++ Online Compiler
Example: Matrix Addition using Multi-dimensional Arrays in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Addition using Multi-dimensional Arrays #include <iostream> using namespace std; int main() { // Step 1: Declare matrix dimensions const int ROWS = 3; const int COLS = 3; // Step 2: Declare two input matrices and one result matrix int matrixA[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int matrixB[ROWS][COLS] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int sumMatrix[ROWS][COLS]; // Matrix to store the sum // Step 3: Perform matrix addition using nested loops cout << "Performing matrix addition..." << endl; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; } } // Step 4: Display the resulting sum matrix cout << "\nResultant Matrix (A + B):" << endl; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { cout << sumMatrix[i][j] << "\t"; } cout << endl; // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS