C++ Online Compiler
Example: Matrix Addition and Subtraction in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Addition and Subtraction #include <iostream> using namespace std; // Function to get matrix input from the user void getMatrixInput(int matrix[][10], int rows, int cols, const char* matrixName) { cout << "Enter elements for " << matrixName << " (" << rows << "x" << cols << "):" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << "Enter element at [" << i << "][" << j << "]: "; cin >> matrix[i][j]; } } } // Function to display a matrix void displayMatrix(int matrix[][10], int rows, int cols, const char* resultType) { cout << "\nResulting " << resultType << " Matrix:" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << matrix[i][j] << "\t"; } cout << endl; } } int main() { int rows1, cols1, rows2, cols2; int matrix1[10][10], matrix2[10][10], sumMatrix[10][10], diffMatrix[10][10]; // Step 1: Get dimensions for the first matrix cout << "Enter number of rows for Matrix 1 (max 10): "; cin >> rows1; cout << "Enter number of columns for Matrix 1 (max 10): "; cin >> cols1; // Step 2: Get elements for the first matrix getMatrixInput(matrix1, rows1, cols1, "Matrix 1"); // Step 3: Get dimensions for the second matrix cout << "\nEnter number of rows for Matrix 2 (max 10): "; cin >> rows2; cout << "Enter number of columns for Matrix 2 (max 10): "; cin >> cols2; // Step 4: Get elements for the second matrix getMatrixInput(matrix2, rows2, cols2, "Matrix 2"); // Step 5: Check compatibility for addition and subtraction if (rows1 != rows2 || cols1 != cols2) { cout << "\nError: Matrices must have the same dimensions for addition and subtraction." << endl; return 1; // Indicate an error } // Step 6: Perform Matrix Addition for (int i = 0; i < rows1; ++i) { for (int j = 0; j < cols1; ++j) { sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } displayMatrix(sumMatrix, rows1, cols1, "Addition"); // Step 7: Perform Matrix Subtraction for (int i = 0; i < rows1; ++i) { for (int j = 0; j < cols1; ++j) { diffMatrix[i][j] = matrix1[i][j] - matrix2[i][j]; } } displayMatrix(diffMatrix, rows1, cols1, "Subtraction"); return 0; }
Output
Clear
ADVERTISEMENTS