C++ Program to Add Two Matrices

1. Introduction

Matrix addition is one of the fundamental operations in matrix arithmetic. It involves adding corresponding elements of two matrices to produce a third matrix. In this blog post, we'll learn how to write a C++ program that performs the addition of two matrices.

2. Program Overview

1. Define two matrices of the same dimensions.

2. Initialize a result matrix with the same dimensions.

3. Traverse each row and column.

4. For each element, add corresponding elements of the two matrices and store the result in the result matrix.

5. Display the result matrix.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    int r, c, a[100][100], b[100][100], sum[100][100];

    cout << "Enter the number of rows and columns of matrices: ";
    cin >> r >> c;

    cout << "\nEnter elements of the 1st matrix:\n";
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < c; ++j)
            cin >> a[i][j];

    cout << "\nEnter elements of the 2nd matrix:\n";
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < c; ++j)
            cin >> b[i][j];

    // Adding the two matrices
    for (int i = 0; i < r; ++i)
        for (int j = 0; j < c; ++j)
            sum[i][j] = a[i][j] + b[i][j];

    cout << "\nSum of the matrices:\n";
    for (int i = 0; i < r; ++i) {
        for (int j = 0; j < c; ++j) {
            cout << sum[i][j] << "  ";
            if (j == c - 1)
                cout << endl;
        }
    }

    return 0;
}

Output:

Enter the number of rows and columns of matrices: 2 2
Enter elements of the 1st matrix:
1 2
3 4
Enter elements of the 2nd matrix:
5 6
7 8
Sum of the matrices:
6  8  
10  12  

4. Step By Step Explanation

1. Matrix Initialization: We start by defining and taking input for two matrices a and b of dimensions r x c.

2. Addition Loop: We traverse each element of both matrices and add their corresponding elements, storing the result in the sum matrix.

3. Output: We print out the resulting sum matrix.

Matrix addition is an elemental operation and forms the basis for many complex matrix manipulations in linear algebra.

Comments