Matrix Addition In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Matrix Addition In C++

Matrix Addition In C++

BLUF: Mastering Matrix Addition In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Matrix Addition In C++

C++ is renowned for its efficiency. Learn how Matrix Addition In C++ enables low-level control and high-performance computing in the tutorial below.

Matrix addition in C++ is a fundamental process that combines two matrices to produce a new matrix. Matrices, which are arrays of numbers arranged in rows and columns, are utilized for this operation. The resulting matrix is created by summing up the corresponding elements from each of the original matrices.

We utilize nested loops to iterate over the rows and columns of the matrices for performing matrix addition in C++. Within these loops, we access the individual elements of each matrix, sum them up, and then save the outcomes in a fresh matrix.

Matrix addition is commonly employed in fields such as computer graphics, scientific computation, and data analysis. It facilitates the merging of information from multiple matrices and their respective mathematical functions. Grasping the concept of matrix addition in C++ lays the groundwork for tackling advanced matrix manipulations and computations.

Understanding Matrices and their Representation

Matrices are mathematical constructs consisting of a rectangular arrangement of elements grouped into rows and columns. They find extensive application across diverse fields such as mathematics, computer science, physics, and data analytics.

Each constituent in a matrix is distinguished by its position, defined by a row index and a column index. The dimensions of a matrix are determined by the number of rows and columns it contains. To illustrate, a matrix with m rows and n columns is denoted as an m x n matrix.

Matrix representations can vary based on the specific computer programming language or mathematical system being utilized. In languages such as C++, arrays are commonly employed for the purpose of depicting matrices.

In a 2D array structure, individual matrix rows are stored as distinct arrays. Subsequently, these arrays are merged to construct the complete matrix. To retrieve specific elements, a pair of indices is employed: one for the row and another for the column.

For instance, let's take a matrix denoted as A containing three rows and four columns:

Example

A = [ 1 2 3 4
5 6 7 8
9 10 11 12 ]

In C++, this matrix can be depicted using a two-dimensional array in the following manner:

Example

int A[3][4] = { {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12} };

The elements of the matrix are saved in a unified continuous memory block. The initial index represents the row, and the subsequent one represents the column.

Sparse matrices store only non-zero elements and their corresponding indices, while linked lists represent each element with a node containing its value, row index, and column index. These alternative ways of representing matrices are beneficial for managing large matrices with numerous zero values efficiently. Proficiency in matrix representation is essential for executing addition, subtraction, multiplication, and inversion operations. This knowledge enables us to retrieve and modify specific elements and perform operations on entire rows or columns.

Algorithm for Matrix Addition in C++

Here is a C++ algorithm for matrix addition:

  • Begin by defining two matrices with the same dimensions. Let's call them M atrix A and Matrix B .
  • To store the result of the addition, create a new matrix Matrix C with the same dimensions as Matrix A and Matrix B .
  • Use nested loops to iterate through each element of the matrices, with the outer loop iterating over the rows and the inner loop iterating over the columns.
  • Access the matching items from Matrix A and Matrix B at the current row and column location.
  • Add the elements' values from Matrix A and Matrix B
  • Put the total in the relevant row and column location of Matrix C .
  • Steps 4-6 should be repeated for all items in the matrix, ensuring the iterations cover the complete range of rows and columns.
  • Matrix C will hold the result of the addition of Matrix A and Matrix B when the iterations are completed.
  • Matrix C can then be used for other processes or shown as the appropriate result.

This function in C++ enables you to sum corresponding elements from two matrices and save the outcome in a fresh matrix.

Implementation in C++

Example

Code
#include <iostream>
using namespace std;

// Function to perform matrix addition
void matrixAddition(int A[][3], int B[][3], int C[][3], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
       for (int j = 0; j < cols; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }
}

// Function to display the matrix
void displayMatrix(int matrix[][3], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    const int rows = 3;
    const int cols = 3;

    int matrixA[rows][cols] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int matrixB[rows][cols] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    int matrixC[rows][cols];

    // Perform matrix addition
    matrixAddition(matrixA, matrixB, matrixC, rows, cols);

    // Display the matrices
    cout << "Matrix A:" << endl;
    displayMatrix(matrixA, rows, cols);

    cout << "Matrix B:" << endl;
    displayMatrix(matrixB, rows, cols);

    cout << "Matrix C (Result of Addition):" << endl;
    displayMatrix(matrixC, rows, cols);

    return 0;
}

The output of the above program will be:

Example

Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
Matrix C (Result of Addition):
10 10 10
10 10 10
10 10 10

Explanation:

In this iteration, the matrix addition function executes matrix summation by iterating over the elements of two matrices, denoted as A and B, and saving the result in a separate matrix C. The display matrix function is employed to showcase the matrices.

In the primary function, we establish two matrices, matrixA and matrixB, assigning them their corresponding values. Furthermore, a matrix C is defined to store the summation outcome.

The function for adding matrices is subsequently executed on the matrices matrixA, matrixB, and matrixC along with the specified number of rows and columns. Following this, the original matrices matrixA and matrixB, as well as the newly computed matrixC, are showcased using the display matrix functionality.

Upon initiating this program, it will execute matrix addition and exhibit both the initial and final matrices.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience