C++ Program to Perform Matrix Subtraction

C++ Program to Perform Matrix Subtraction

Matrices are an essential part of mathematics and computer programming, often used in areas like graphics, engineering, and scientific computations. While matrix addition is widely practiced, matrix subtraction is equally important. Matrix subtraction involves taking two matrices of the same size and subtracting corresponding elements to form a new matrix. Learning how to perform matrix subtraction in C++ is a great way for beginners to practice nested loops, array handling, and element-wise operations, laying the groundwork for more advanced matrix operations.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Program 1: Matrix Subtraction Using User Input

This program allows the user to input the elements of two matrices and then calculates their difference. It helps beginners understand how arrays and loops work together in C++ for element-wise operations.

#include <iostream>

using namespace std;

int main() {

    int rows, cols;

    cout << "Enter the number of rows: " << endl;
    cin >> rows;

    cout << "Enter the number of columns: " << endl;
    cin >> cols;

    int matrix1[rows][cols], matrix2[rows][cols], difference[rows][cols];

    cout << "Enter elements of first matrix:" << endl;

    for(int i = 0; i < rows; i++) {

        for(int j = 0; j < cols; j++) {
            cin >> matrix1[i][j];
        }

    }

    cout << "Enter elements of second matrix:" << endl;
    for(int i = 0; i < rows; i++) {

        for(int j = 0; j < cols; j++) {
            cin >> matrix2[i][j];
        }

    }

    for(int i = 0; i < rows; i++) {

        for(int j = 0; j < cols; j++) {
            difference[i][j] = matrix1[i][j] - matrix2[i][j];
        }

    }

    cout << "Difference of the matrices:" << endl;

    for(int i = 0; i < rows; i++) {

        for(int j = 0; j < cols; j++) {
            cout << difference[i][j] << " ";
        }

        cout << endl;

    }

    return 0;

}

In this program, the user enters the size and elements of two matrices. Nested loops go through each row and column, subtracting the corresponding elements and storing them in a new matrix. Beginners can clearly see how arrays and loops interact to perform element-wise operations, which is essential for all matrix-based programming.

Program 2: Matrix Subtraction with a Single Predefined Matrix

Sometimes, working with predefined values helps beginners focus on the logic rather than input. This program demonstrates matrix subtraction with predefined matrices.

#include <iostream>

using namespace std;

int main() {

    int matrix1[2][2] {{8, 6}, {4, 2}};
    int matrix2[2][2] {{1, 2}, {3, 4}};
    int difference[2][2];

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            difference[i][j] = matrix1[i][j] - matrix2[i][j];
        }

    }

    cout << "Difference of the predefined matrices:" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << difference[i][j] << " ";
        }

        cout << endl;

    }

    return 0;

}

In this program, two 2×2 matrices are already defined. Nested loops subtract corresponding elements and store the results in a new matrix. Beginners can focus entirely on the logic of subtraction and observe the element-wise operations without entering values manually, which is helpful for testing and learning.

Program 3: Matrix Subtraction with Multiple Predefined Matrices

For slightly more advanced practice, this program demonstrates how to subtract two 3×3 predefined matrices.

#include <iostream>

using namespace std;

int main() {

    int matrix1[3][3] {{9,8,7}, {6,5,4}, {3,2,1}};
    int matrix2[3][3] {{1,2,3}, {4,5,6}, {7,8,9}};
    int difference[3][3];

    for(int i = 0; i < 3; i++) {

        for(int j = 0; j < 3; j++) {
            difference[i][j] = matrix1[i][j] - matrix2[i][j];
        }

    }

    cout << "Difference of the 3x3 matrices:" << endl;

    for(int i = 0; i < 3; i++) {

        for(int j = 0; j < 3; j++) {
            cout << difference[i][j] << " ";
        }

        cout << endl;

    }

    return 0;

}

This example illustrates how matrix subtraction scales to larger matrices. Nested loops handle each element systematically, demonstrating to beginners how C++ arrays efficiently store structured data and how loops traverse these structures to perform operations.

Program 4: Colorful Matrix Display

This program demonstrates how to subtract two matrices and display the matrices and their difference in different colors using ANSI escape codes. It’s an interactive way to help beginners understand the element-wise subtraction process.

#include <iostream>

using namespace std;

int main() {

    int matrix1[2][2] {{8, 6}, {4, 2}};
    int matrix2[2][2] {{1, 2}, {3, 4}};
    int difference[2][2];

    // Calculate difference of matrices
    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            difference[i][j] = matrix1[i][j] - matrix2[i][j];
        }

    }

    // Display first matrix in blue
    cout << "\033[1;34mMatrix 1:\033[0m" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << "\033[1;34m" << matrix1[i][j] << " \033[0m";
        }

        cout << endl;

    }

    // Display second matrix in green
    cout << "\033[1;32mMatrix 2:\033[0m" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << "\033[1;32m" << matrix2[i][j] << " \033[0m";
        }

        cout << endl;

    }

    // Display difference matrix in yellow
    cout << "\033[1;33mDifference of Matrices:\033[0m" << endl;

    for(int i = 0; i < 2; i++) {

        for(int j = 0; j < 2; j++) {
            cout << "\033[1;33m" << difference[i][j] << " \033[0m";
        }

        cout << endl;

    }

    return 0;

}

In this program, the two predefined 2×2 matrices are subtracted element by element using nested loops. The ANSI escape codes like \033[1;34m and \033[1;32m change the color of the text displayed on the console. The first matrix appears in blue, the second in green, and the difference in yellow. This color-coding helps beginners visually distinguish between the original matrices and the result, making it easier to follow the subtraction logic.

Frequently Asked Questions (FAQ)

Understanding matrix subtraction in C++ often raises some common questions. Here are the answers in a beginner-friendly way.

Q1: What is matrix subtraction?
A1: Matrix subtraction is the process of subtracting each element of one matrix from the corresponding element of another matrix. Both matrices must be of the same size.

Q2: Can I subtract matrices of different sizes?
A2: No. For subtraction, both matrices must have the same number of rows and columns. Otherwise, the operation is undefined.

Q3: How are matrices stored in C++?
A3: Matrices are stored as two-dimensional arrays, where each row contains a one-dimensional array of elements.

Q4: Why do we use nested loops for matrix subtraction?
A4: Nested loops allow us to traverse rows and columns systematically. The outer loop handles rows, and the inner loop handles columns, ensuring each element is processed.

Q5: Are predefined matrices useful for learning?
A5: Yes. Predefined matrices let beginners focus on logic and calculations without worrying about input, making it easier to understand the process.

Conclusion

Matrix subtraction in C++ is a fundamental operation that strengthens your understanding of arrays, nested loops, and element-wise operations. By practicing with user input, a single predefined matrix, and multiple predefined matrices, beginners can gain confidence in handling structured data. Regular practice with different matrix sizes and values helps build problem-solving skills and prepares you for more advanced topics in C++ programming.

Additional & References

Beginners are encouraged to explore other matrix operations like addition, multiplication, and transpose to enhance their understanding of arrays and nested loops. Practicing these operations prepares you for complex algorithms and real-world applications.

Scroll to Top