C++ Online Compiler
Example: Add Two 4x4 Matrices in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Add Two 4x4 Matrices #include <iostream> // Required for input/output operations int main() { // Step 1: Declare three 4x4 matrices // matrix1 and matrix2 will store the input matrices // sumMatrix will store the result of the addition int matrix1[4][4]; int matrix2[4][4]; int sumMatrix[4][4]; // Step 2: Get input for the first matrix (matrix1) std::cout << "Enter elements for the first 4x4 matrix:" << std::endl; for (int i = 0; i < 4; ++i) { // Loop for rows for (int j = 0; j < 4; ++j) { // Loop for columns std::cout << "Enter element at position [" << i << "][" << j << "]: "; std::cin >> matrix1[i][j]; } } // Step 3: Get input for the second matrix (matrix2) std::cout << "\nEnter elements for the second 4x4 matrix:" << std::endl; for (int i = 0; i < 4; ++i) { // Loop for rows for (int j = 0; j < 4; ++j) { // Loop for columns std::cout << "Enter element at position [" << i << "][" << j << "]: "; std::cin >> matrix2[i][j]; } } // Step 4: Perform matrix addition // Add corresponding elements of matrix1 and matrix2 and store in sumMatrix for (int i = 0; i < 4; ++i) { // Loop for rows for (int j = 0; j < 4; ++j) { // Loop for columns sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } // Step 5: Display the resulting sum matrix std::cout << "\nResultant Sum Matrix:" << std::endl; for (int i = 0; i < 4; ++i) { // Loop for rows for (int j = 0; j < 4; ++j) { // Loop for columns std::cout << sumMatrix[i][j] << "\t"; // Print element followed by a tab for formatting } std::cout << std::endl; // Move to the next line after printing each row } return 0; // Indicate successful program execution }
Output
Clear
ADVERTISEMENTS