C++ Online Compiler
Example: AddTwo4x4Matrices in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// AddTwo4x4Matrices #include <iostream> using namespace std; int main() { const int SIZE = 4; // Define matrix size // Step 1: Declare and initialize two 4x4 matrices int matrixA[SIZE][SIZE] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 1, 2, 3}, {4, 5, 6, 7} }; int matrixB[SIZE][SIZE] = { {7, 6, 5, 4}, {3, 2, 1, 0}, {1, 2, 3, 4}, {5, 6, 7, 8} }; // Step 2: Declare a 4x4 matrix to store the sum int sumMatrix[SIZE][SIZE]; // Step 3: Print matrixA for verification cout << "Matrix A:" << endl; for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { cout << matrixA[i][j] << " "; } cout << endl; } cout << endl; // Step 4: Print matrixB for verification cout << "Matrix B:" << endl; for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { cout << matrixB[i][j] << " "; } cout << endl; } cout << endl; // Step 5: Perform matrix addition using nested loops // Iterate through rows for (int i = 0; i < SIZE; ++i) { // Iterate through columns for (int j = 0; j < SIZE; ++j) { sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; } } // Step 6: Print the resulting sumMatrix cout << "Sum of Matrix A and Matrix B (sumMatrix):" << endl; for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { cout << sumMatrix[i][j] << " "; } cout << endl; } return 0; }
Output
Clear
ADVERTISEMENTS