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> // Required for input/output operations using namespace std; // Using the standard namespace int main() { // Step 1: Define matrix dimensions (rows and columns) const int ROWS = 2; // Number of rows const int COLS = 3; // Number of columns // Step 2: Declare and initialize the first matrix (matrixA) int matrixA[ROWS][COLS] = { {1, 2, 3}, {4, 5, 6} }; // Step 3: Declare and initialize the second matrix (matrixB) int matrixB[ROWS][COLS] = { {7, 8, 9}, {10, 11, 12} }; // Step 4: Declare a result matrix (sumMatrix) to store the sum // It must have the same dimensions as matrixA and matrixB int sumMatrix[ROWS][COLS]; // Step 5: Perform matrix addition using nested loops // Outer loop iterates through rows for (int i = 0; i < ROWS; ++i) { // Inner loop iterates through columns for (int j = 0; j < COLS; ++j) { // Add corresponding elements of matrixA and matrixB // Store the result in sumMatrix at the same position sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; } } // Step 6: Display the resulting sum matrix cout << "Sum of the matrices:" << endl; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLS; ++j) { // Print each element followed by a space cout << sumMatrix[i][j] << " "; } // Move to the next line after printing all elements of a row cout << endl; } return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS