TutorialStudyMite

Subtraction of matrices in C++

JJuhi Kamdar5 min read
Beginner friendly

Try it first

Matrix Difference Calculator

Give it a try before seeing the solution in this article.

Give it a try

Track completion, mastery, and revision.

Understanding Matrix Subtraction

Matrix subtraction is a fundamental operation in linear algebra. To subtract two matrices, they must meet a crucial condition: both matrices must have the exact same dimensions (i.e., the same number of rows and the same number of columns).

If this condition is met, the subtraction is performed by subtracting their corresponding elements. This means that if you have two matrices, $A$ and $B$, their difference $C = A - B$ will be a new matrix where each element $C_{ij}$ is calculated as:

$C_{ij} = A_{ij} - B_{ij}$

Here, $A_{ij}$ refers to the element in the $i$-th row and $j$-th column of matrix $A$, and similarly for $B_{ij}$ and $C_{ij}$.

Example of Matrix Subtraction

Let's consider two 2x2 matrices, $A$ and $B$:

$A = \begin{pmatrix} 5 & 2 \ 1 & 7 \end{pmatrix}$

$B = \begin{pmatrix} 3 & 1 \ 0 & 4 \end{pmatrix}$

To find $C = A - B$, we subtract the corresponding elements:

$C = \begin{pmatrix} 5-3 & 2-1 \ 1-0 & 7-4 \end{pmatrix} = \begin{pmatrix} 2 & 1 \ 1 & 3 \end{pmatrix}$

Algorithm for Matrix Subtraction

The process of subtracting two matrices can be broken down into these steps:

  1. Input Dimensions: Obtain the number of rows and columns for both matrices.
  2. Validate Dimensions: Check if the dimensions of the two matrices are identical. If they are not, subtraction is not possible, and the program should indicate an error or terminate.
  3. Input Elements: Read the elements for both matrices from the user.
  4. Perform Subtraction: Iterate through each corresponding element of the two matrices and subtract them. Store the result in a new matrix.
  5. Display Result: Print the elements of the resulting matrix.

C++ Implementation

In C++, matrices are typically represented using two-dimensional arrays. The following code demonstrates how to subtract two matrices using fixed-size arrays.

Note on Fixed-Size Arrays: The example uses fixed-size arrays (e.g., int a[5][5]). While simple for demonstration, this approach limits the maximum size of matrices you can handle. For more flexible and robust applications, consider using dynamic memory allocation (e.g., pointers to pointers) or std::vector<std::vector<int>> which allows for matrices of arbitrary sizes determined at runtime.

Example Code

#include <iostream>

// Function prototypes
void subtract(int a[5][5], int b[5][5], int row, int col);
void display(int c[5][5], int row, int col);

int main() {
    int a[5][5], b[5][5];
    int r1, c1, r2, c2;

    std::cout << "\nEnter rows for first matrix: ";
    std::cin >> r1;
    std::cout << "Enter columns for first matrix: "; // Corrected prompt
    std::cin >> c1;

    std::cout << "\nEnter rows for second matrix: ";
    std::cin >> r2;
    std::cout << "Enter columns for second matrix: "; // Corrected prompt
    std::cin >> c2;

    // Check if matrices can be subtracted (must have same dimensions)
    if (r1 != r2 || c1 != c2) {
        std::cout << "\nError: Matrices must have the same dimensions for subtraction." << std::endl;
        return 1; // Indicate an error
    }

    // Storing elements of the first matrix.
    std::cout << "\nEnter elements of first matrix:\n";
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c1; j++) {
            std::cin >> a[i][j];
        }
    }

    // Storing elements of the second matrix.
    std::cout << "\nEnter elements of second matrix:\n";
    for (int i = 0; i < r2; i++) {
        for (int j = 0; j < c2; j++) {
            std::cin >> b[i][j];
        }
    }

    std::cout << "\nMatrix A:\n";
    display(a, r1, c1);

    std::cout << "\nMatrix B:\n"; // Corrected prompt
    display(b, r2, c2);

    // Call the function to subtract matrices a and b.
    subtract(a, b, r1, c1);

    return 0;
}

// Function to perform matrix subtraction
void subtract(int a[5][5], int b[5][5], int row, int col) {
    int c[5][5]; // Matrix to store the result

    // Perform element-wise subtraction
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            c[i][j] = a[i][j] - b[i][j];
        }
    }

    // Display the resulting matrix
    std::cout << "\nMatrix C after Subtraction is:\n";
    display(c, row, col);
}

// Function to display a matrix
void display(int c[5][5], int row, int col) {
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            std::cout << c[i][j] << " ";
        }
        std::cout << "\n";
    }
}

Code Explanation

  • main function:
    • Declares two 2D arrays, a and b, to store the input matrices, and variables for their dimensions (r1, c1, r2, c2).
    • Prompts the user to enter the dimensions for both matrices.
    • Crucially, it checks if r1 != r2 || c1 != c2. If the dimensions don't match, it prints an error and exits, preventing invalid subtraction.
    • Takes input for the elements of both matrices.
    • Calls the display function to show the original matrices A and B.
    • Calls the subtract function, passing the two matrices and their dimensions.
  • subtract function:
    • Takes two input matrices (a, b) and their row/col dimensions.
    • Declares a new 2D array c to store the result of the subtraction.
    • Uses nested loops to iterate through each element position (i, j).
    • Calculates c[i][j] = a[i][j] - b[i][j], performing the element-wise subtraction.
    • Finally, it calls the display function to print the resulting matrix C.
  • display function:
    • Takes a matrix (c) and its row/col dimensions.
    • Uses nested loops to iterate through the matrix elements.
    • Prints each element followed by a space.
    • After each row, it prints a newline character (\n) to format the output correctly.

Sample Output

Enter rows for first matrix: 3
Enter columns for first matrix: 3

Enter rows for second matrix: 3
Enter columns for second matrix: 3

Enter elements of first matrix:
76 35 24
24 56 24
86 25 75

Enter elements of second matrix:
5 7 8
7 3 6
6 3 7

Matrix A:
76 35 24 
24 56 24 
86 25 75 

Matrix B:
5 7 8 
7 3 6 
6 3 7 

Matrix C after Subtraction is:
71 28 16 
17 53 18 
80 22 68 

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.