Subtraction of Two Matrices in C Language

subtraction-of-two-matrices-in-c-language

Program Description:

In our previous articles, we looked at the Read and Print Matrices Program, In today’s article, We are going to look at the program to perform the Subtraction of Two Matrices in C programming language. The Program accepts two matrices of the same order and calculates the element-wise subtraction of the given matrices.

📢This program is part of the Array Practice Programs Series.

How to Subtract Two Matrices?

Let’s say we have two matrices X and Y with the size of the row as rows and column size as columns

We can only Subtract matrices if they have the same number of rowsand columns. So we need to make sure both matrices X and Y should have the same size( Order)

So Subtraction of Two Matrices can be calculated by subtracting corresponding elements from both matrices. (Element-wise Subtraction)

If Matrix X = [xij] and Y = [yij] are two matrices with the same rows size and column size.

Then the Subtraction of matrices X and Y is: X-Y = [xij] – [yij]

Example – Subtraction of Two Matrices:

Matrix-X:

Matrix – Y:

Subtraction Z = X – Y:

Let’s look at the graphical representation of the Subtraction operation of Matrices.

subtraction-of-two-matrix-in-c

Subtraction of Two Matrices in C Program Explanation:

Let’s look at the step-by-step instruction for the Subtraction of Two Matrices in the C program.

  1. Create two integer constants named ROWS and COLUMNS, Which holds the max number of rows and columns. Please change this number if you want to play with the large arrays. 🤞
  2. Start the Program by declaring three Matrices (2D Arrays). They are X matrix, Y matrix, and Z Matrix. The row size and column size of the matrices are ROWS and COLUMNS respectively.
  3. Prompt the user to provide the desired Row size and Column Size, and store them in the variables rows and columns respectively. (Note, These rows and columns are small letters – C is Case Sensitive language)
  4. Check for array bounds using the (rows >= ROWS || rows <= 0 || columns >= COLUMNS || columns <= 0) condition, And display an error message if the row/column sizeis beyond the present limits.
  5. Take the user input for Matrix-X, We need to create two For Loops, One For Loop will iterate over the rows, and the Second For Loop will iterate over the columns
  6. Create the First For Loop ( Outer Loop), Start the iteration from i=0 and go till the i<rows (i.e for(i=0; i<rows; i++) ). The Outer Loop will iterate over the rows and At Each iteration of the Outer Loop,
    • Create the second For Loop ( Inner Loop). This loop is a Nested loop that will be inside the Outer Loop. Start the Loop from j=0 and go till the j<columns (i.e for(j=0; j<columns; j++) ). The Inner Loop will iterate over the columns. At each iteration of the Inner Loop
      • Prompt the user to provide the Matrix or 2D Array element and Read the element using the scanf function and Update the values[i][j] element.
      • Repeat the above step for all elements in the 2D array or matrix
  7. Repeat the step-5 to Take the Second Matrix ( Matrix-Y) elements from the user.
  8. To Calculate the Subtraction of Two Matrices, We again need to use two nested For loops to iterate over the matrix elements.
  9. Create Outer For Loop ( iterates over rows) – for(i=0; i<rows; i++)
    • Create Inner For loop (iterates over columns) – for(j=0; j<columns; j++)
      • Subtract the Y[i][j] element from the X[i][j] and store the result in Z[i][j]
      • which is equal to Z[i][j] = X[i][j] - Y[i][j];
  10. Once the above step-9 is finished, The Matrix-Z contains the Subtraction of Matrix-X and Matrix-Y.
  11. Display the Results( Maxtrix-Z) using another Two For loops.
  12. Create Outer For Loop. Start from i=0 to i<rowsfor(i=0; i<rows; i++)
    • Create Inner For Loop, Start from j=0 to j<columnsfor(j=0; j<columns; j++)
      • Print the 2D Array or Matrix Element Z[i][j] using the printf function.
      • printf("%d ", Z[i][j]);
  13. Stop the Program.

Program to Perform the Subtraction of Two Matrices in C Language:

Here is the program to Subtract two matrices in C programming language

Program Output:

Compile the program using your favorite compiler. We are using the GCC compiler on Linux (Ubuntu)

$ gcc subtract-two-matrices.c

The above command generated the a.out file. which is an executable file, Run the executable file.

Test 1: Provide the matrix elements and observe the output

subtraction-of-two-matrices-in-c-program-output

As we can see from the above output, The program is generating the desired results. Let’s look at a few more examples.

Test 2: Negative tests – when the user provides out-of-bounds sizes

As excepted, The program generated the error message. Invalid Rows or Columns size, Please Try again

Subtraction of Two Matrices in C using Functions:

We have used a single function to calculate the subtraction of the matrices in the above program, Let’s divide the above program and convert it into the sub-functions, where each function does a specific task. So that the readability and debuggability of the program increase.

Here is the modified version of the above Matrix subtraction program.

In the above program, We have defined three user-defined functions (except the main), They are.

  1. The readMatrix() function – Used to read the elements from the user and update the given matrix
    • Function Prototypevoid readMatrix(int rows, int columns, int A[rows][columns])
    • The readMatrix() function takes three formal arguments which are rows, columns, and Matrix A.
    • This function uses Two For loops to iterate over the given matrix A and updates its elements by using the scanf function – scanf(“%d”, &A[i][j]);
    • The readMatrix() function doesn’t return anything back to the caller. So return type is void.
    • As the arrays are passed by the address/reference, All the changes made to the Matrix-A in the readMatrix() function will be visible in the Caller Function (i.e main() function).
  2. The displayMatrix() function is used to print the Matrix elements on the Standard Output.
    • The prototype of displayMatrix function is void displayMatrix(int rows, int columns, int A[rows][columns])
    • Similar to the readMatrix() function, The displayMatrix() function also takes three formal arguments. i.e rows, columns, and A[][] (2D Array)
    • The displayMatrix() function uses Two For loops to iterate over the A matrix and print the elements of the matrix. – printf("%d ", A[i][j]);
  3. The subtractMatrices() function – This function performs the subtraction operation of the Matrix-X and Matrix-Y
    • Function Prototypevoid subtractMatrices(int rows, int columns, int X[rows][columns], int Y[rows][columns], int Z[rows][columns])
    • As you can see from the above prototype, This function takes Five Formal Arguments which are rows, columns, matrix X, matrix Y, and matrix Z.
    • The addMatrices() function uses two for loops to iterate over the elements of the Matrices X and Y and Performs the element-wise subtraction and stores the results in the Matrix-ZZ[i][j] = X[i][j] - Y[i][j];

Program Output:

Let’s compile and Run the Program.

subtract-of-two-matrices-using-functions-program-output

As we can see from the above output, The program initially prompted for the Row Size and Column Size of both matrices and followed by the values for all elements of the two matrices. Finally, Program Calculated and displayed the subtraction of given Matrices on the console.

The program displayed the error message if the size is beyond present ROWS or COLUMNS.

Related Array Practice Programs:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

2 Responses

  1. […] C Program to Subtract Two Matrices […]

  2. […] C Program to Subtract Two Matrices […]

Leave a Reply