C++ Online Compiler
Example: Add Two 3x3 Matrices in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Add Two 3x3 Matrices #include <iostream> using namespace std; int main() { // Step 1: Declare three 3x3 integer matrices int matrixA[3][3]; int matrixB[3][3]; int sumMatrix[3][3]; // Step 2: Get elements for the first matrix from the user cout << "Enter elements for the first 3x3 matrix (9 integers):" << endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cout << "Enter element A[" << i << "][" << j << "]: "; cin >> matrixA[i][j]; } } // Step 3: Get elements for the second matrix from the user cout << "\nEnter elements for the second 3x3 matrix (9 integers):" << endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cout << "Enter element B[" << i << "][" << j << "]: "; cin >> matrixB[i][j]; } } // Step 4: Perform matrix addition // Iterate through rows for (int i = 0; i < 3; ++i) { // Iterate through columns for (int j = 0; j < 3; ++j) { sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; } } // Step 5: Display the resulting sum matrix cout << "\nSum of the two matrices is:" << endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cout << sumMatrix[i][j] << " "; } cout << endl; // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS