C++ Online Compiler
Example: Matrix Addition in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Addition #include <iostream> #include <vector> // For dynamic arrays using namespace std; int main() { int rows1, cols1, rows2, cols2; // Step 1: Get dimensions for the first matrix cout << "Enter number of rows for matrix 1: "; cin >> rows1; cout << "Enter number of columns for matrix 1: "; cin >> cols1; // Step 2: Get dimensions for the second matrix cout << "Enter number of rows for matrix 2: "; cin >> rows2; cout << "Enter number of columns for matrix 2: "; cin >> cols2; // Step 3: Check if matrices can be added if (rows1 != rows2 || cols1 != cols2) { cout << "Matrices cannot be added! Dimensions must be the same." << endl; return 1; // Indicate an error } // Declare matrices using std::vector for dynamic sizing // matrix1 and matrix2 store the input matrices // sumMatrix will store the result of the addition vector<vector<int>> matrix1(rows1, vector<int>(cols1)); vector<vector<int>> matrix2(rows2, vector<int>(cols2)); vector<vector<int>> sumMatrix(rows1, vector<int>(cols1)); // Step 4: Input elements for matrix 1 cout << "\nEnter elements for matrix 1:" << endl; for (int i = 0; i < rows1; ++i) { for (int j = 0; j < cols1; ++j) { cout << "Enter element a[" << i << "][" << j << "]: "; cin >> matrix1[i][j]; } } // Step 5: Input elements for matrix 2 cout << "\nEnter elements for matrix 2:" << endl; for (int i = 0; i < rows2; ++i) { for (int j = 0; j < cols2; ++j) { cout << "Enter element b[" << i << "][" << j << "]: "; cin >> matrix2[i][j]; } } // Step 6: Perform matrix addition // Iterate through each row for (int i = 0; i < rows1; ++i) { // Iterate through each column for (int j = 0; j < cols1; ++j) { // Add corresponding elements and store in sumMatrix sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } // Step 7: Display the resulting sum matrix cout << "\nResultant Matrix (Sum):" << endl; for (int i = 0; i < rows1; ++i) { for (int j = 0; j < cols1; ++j) { cout << sumMatrix[i][j] << " "; } cout << endl; // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS