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:
1 2 3 |
38 48 74 87 23 45 67 23 65 |
Matrix – Y:
1 2 3 |
12 37 98 76 23 45 34 51 73 |
Subtraction Z = X – Y:
1 2 3 |
26 11 -24 11 0 0 33 -28 -8 |
Let’s look at the graphical representation of the Subtraction operation of Matrices.
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.
- 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. 🤞
- 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.
- 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)
- 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.
- 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
- 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
- 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
- Repeat the step-5 to Take the Second Matrix ( Matrix-Y) elements from the user.
- To Calculate the Subtraction of Two Matrices, We again need to use two nested For loops to iterate over the matrix elements.
- 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];
- Create Inner For loop (iterates over columns) – for(j=0; j<columns; j++)
- Once the above step-9 is finished, The Matrix-Z contains the Subtraction of Matrix-X and Matrix-Y.
- Display the Results( Maxtrix-Z) using another Two For loops.
- Create Outer For Loop. Start from i=0 to i<rows – for(i=0; i<rows; i++)
- Create Inner For Loop, Start from j=0 to j<columns – for(j=0; j<columns; j++)
- Print the 2D Array or Matrix Element Z[i][j] using the printf function.
- printf("%d ", Z[i][j]);
- Create Inner For Loop, Start from j=0 to j<columns – for(j=0; j<columns; j++)
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
/* Program to Subtract Two Matrices in C SillyCodes.com */ #include <stdio.h> const int ROWS=100; const int COLUMNS=100; int main() { // Declare three matrices. // 'X' & 'Y' are Input matrices // 'Z' stores result of 'X' and 'Y' matrices subtraction int X[ROWS][COLUMNS], Y[ROWS][COLUMNS], Z[ROWS][COLUMNS]; int rows, columns, i, j; // Take the Row size and Column size from user printf("Enter the Row size for Matrices(1-%d): ", ROWS); scanf("%d", &rows); printf("Enter the Column Size for Matrices(1-%d): ", COLUMNS); scanf("%d", &columns); // check for array bounds if(rows >= ROWS || rows <= 0 || columns >= COLUMNS || columns <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Take the user input for 1st Matrix - 'X' printf("Enter Elements for the First Matrix(X) of Size %dX%d: \n", rows, columns); for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // printf("X[%d][%d]: ", i, j); scanf("%d", &X[i][j]); } } // Take the user input for 2nd Matrix - 'Y' printf("Enter Elements for the Second Matrix(Y) of Size %dX%d: \n", rows, columns); for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // printf("Y[%d][%d]: ", i, j); scanf("%d", &Y[i][j]); } } // Subtract two matrices 'X'+'Y' element by element for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // Subtract - Element by element subtraction of 'X' and 'Y' Matrices Z[i][j] = X[i][j] - Y[i][j]; } } // Print the Result printf("Subtraction of Two Matrices (Z = X-Y) is : \n"); for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // Print Elements printf("%d ", Z[i][j]); } printf("\n"); } return 0; } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$ ./a.out Enter the Row size for Matrices(1-100): 4 Enter the Column Size for Matrices(1-100): 4 Enter Elements for the First Matrix(X) of Size 4X4: 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 Enter Elements for the Second Matrix(Y) of Size 4X4: 3 8 13 18 23 28 33 38 42 48 53 58 63 68 73 78 Subtraction of Two Matrices (Z = X-Y) is : 2 2 2 2 2 2 2 2 3 2 2 2 2 2 2 2 $ |
As we can see from the above output, The program is generating the desired results. Let’s look at a few more examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$ ./a.out Enter the Row size for Matrices(1-100): 3 Enter the Column Size for Matrices(1-100): 3 Enter Elements for the First Matrix(X) of Size 3X3: 38 48 74 87 23 45 67 23 65 Enter Elements for the Second Matrix(Y) of Size 3X3: 12 37 98 76 23 45 34 51 73 Subtraction of Two Matrices (Z = X-Y) is : 26 11 -24 11 0 0 33 -28 -8 $ |
Test 2: Negative tests – when the user provides out-of-bounds sizes
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$ ./a.out Enter the Row size for Matrices(1-100): 599 Enter the Column Size for Matrices(1-100): 40 Invalid Rows or Columns size, Please Try again $ ./a.out Enter the Row size for Matrices(1-100): 45 Enter the Column Size for Matrices(1-100): 5000 Invalid Rows or Columns size, Please Try again $ ./a.out Enter the Row size for Matrices(1-100): 0 Enter the Column Size for Matrices(1-100): 0 Invalid Rows or Columns size, Please Try again $ |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
/* Program to Subtract Two Matrices in C using functions SillyCodes.com */ #include <stdio.h> const int ROWS=100; const int COLUMNS=100; void subtractMatrices(int rows, int columns, int X[rows][columns], int Y[rows][columns], int Z[rows][columns]); /** * @brief - Read Matrix from the user and update 'A' * * @param rows - Rows in Matrix(2Darray) * @param columns - Columns in 'A' * @param A - 'A' is Matrix or 2D array */ void readMatrix(int rows, int columns, int A[rows][columns]) { int i, j; for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { //printf("A[%d][%d]: ", i, j); scanf("%d", &A[i][j]); } } } /** * @brief - Print the elements of the Matrix * * @param rows - Rows in Matrix(2Darray) * @param columns - Columns in 'A' * @param A[][] - 'A' is a Matrix or 2D array */ void displayMatrix(int rows, int columns, int A[rows][columns]) { int i, j; for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // Print Elements printf("%d ", A[i][j]); } printf("\n"); } } int main() { // Declare three matrices. // 'X' & 'Y' are Input matrices // 'Z' stores result of 'X' and 'Y' matrices subtraction int X[ROWS][COLUMNS], Y[ROWS][COLUMNS], Z[ROWS][COLUMNS]; int rows, columns, i, j; // Take the Row size and Column size from user printf("Enter the Row size for Matrices(1-%d): ", ROWS); scanf("%d", &rows); printf("Enter the Column Size for Matrices(1-%d): ", COLUMNS); scanf("%d", &columns); // check for array bounds if(rows >= ROWS || rows <= 0 || columns >= COLUMNS || columns <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Take the user input for 1st Matrix - 'X' printf("Enter Elements for the First Matrix(X) of Size %dX%d: \n", rows, columns); readMatrix(rows, columns, X); // Take the user input for 2nd Matrix - 'Y' printf("Enter Elements for the Second Matrix(Y) of Size %dX%d: \n", rows, columns); readMatrix(rows, columns, Y); // Subtract two matrices 'X'-'Y' element by element subtractMatrices(rows, columns, X, Y, Z); // Print the Result printf("Subtraction of Two Matrices (Z=X-Y) is : \n"); displayMatrix(rows, columns, Z); return 0; } /** * @brief - Subtract Matrices pointed by 'X' and 'Y' and Store the result in 'Z' * * @param rows - Rows in the Matrices * @param columns - Columns in the Matrices * @param X - First Matrix * @param Y - Second Matrix * @param Z - Resultant Matrix * @return void */ void subtractMatrices(int rows, int columns, int X[rows][columns], int Y[rows][columns], int Z[rows][columns]) { int i, j; for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // Subtract elements from 'X' and 'Y' // Assign to 'z' Z[i][j] = X[i][j] - Y[i][j]; } } } |
In the above program, We have defined three user-defined functions (except the main), They are.
- The
readMatrix() function – Used to read the elements from the user and update the given matrix
- Function Prototype – void 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).
- 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]);
- The
subtractMatrices() function – This function performs the subtraction operation of the
Matrix-X and
Matrix-Y
- Function Prototype – void 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-Z – Z[i][j] = X[i][j] - Y[i][j];
Program Output:
Let’s compile and Run the Program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
$ gcc subtract-two-matrices-func.c $ ./a.out Enter the Row size for Matrices(1-100): 3 Enter the Column Size for Matrices(1-100): 2 Enter Elements for the First Matrix(X) of Size 3X2: 10 20 30 40 50 60 Enter Elements for the Second Matrix(Y) of Size 3X2: 5 15 25 35 45 55 Subtraction of Two Matrices (Z=X-Y) is : 5 5 5 5 5 5 $ ./a.out Enter the Row size for Matrices(1-100): 3 Enter the Column Size for Matrices(1-100): 3 Enter Elements for the First Matrix(X) of Size 3X3: 12 87 34 54 67 87 23 47 82 Enter Elements for the Second Matrix(Y) of Size 3X3: 21 76 23 81 92 43 67 26 18 Subtraction of Two Matrices (Z=X-Y) is : -9 11 11 -27 -25 44 -44 21 64 $ |
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.
1 2 3 4 5 6 7 8 9 |
$ ./a.out Enter the Row size for Matrices(1-100): 9000 Enter the Column Size for Matrices(1-100): 45 Invalid Rows or Columns size, Please Try again $ ./a.out Enter the Row size for Matrices(1-100): 4 Enter the Column Size for Matrices(1-100): 100 Invalid Rows or Columns size, Please Try again $ |
The program displayed the error message if the size is beyond present ROWS or COLUMNS.
Related Array Practice Programs:
- C Program to Reverse the Array Elements
- C Program to Reverse Array Elements using Recursion
- C Program to Sort Array Elements in Ascending order
- C Program to Sort Array in Ascending and Descending Order using QSort function
- C Program to Count Number of Unique Elements in Array
- C Program to Merge Two Arrays
- C Program to Merge Two Sorted Array and Generate Sorted Array
- C Program to Copy array to Another Array
- C Program to Find Second Smallest Element in Array
- C Program to Delete Duplicate Elements in an Array
- C Program to Left Rotate Array by ‘N’ Times
- C Program to Right Rotate Array Elements by ‘N’ Positions
- Linear Search in C Language with Example Programs
- C Program to Count Frequencies of Each Element in the Array
- C Program to Search element in an Array
2 Responses
[…] C Program to Subtract Two Matrices […]
[…] C Program to Subtract Two Matrices […]