Addition of Two Matrices in C Language

addition-of-two-matrices-in-c-language

Program Description:

We have looked at the Reading and Printing Matrices and How to Pass Matrices to functions programs in earlier articles, In today’s article, We will look at the Addition of Two Matrices in C programming language. The program should accept Two Matrices from the user, perform the element-wise addition, and return the results.

Prerequisites:

Before looking at the example input and output of the program, Let’s understand how to Add Two Matrices.

How to Add 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 Add 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 Addition of Two Matrices can be calculated by adding corresponding elements from both matrices. (Element-wise Addition)

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

Then the Addition of matrices X and Y is: X+Y = [xij] + [yij]

Example – Addition of Two Matrices:

Matrix – X:

Matrix – Y:

Addition of Two Matrices X + Y is:

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

addition-of-two-matrix-in-c-language

Let’s look at the program to perform the Addition of Two Matrices in the C programming language.

Addition of Two Matrices in C Program Explanation:

Here is the step-by-step explanation of the Addition of Two Matrices Program.

  1. Start the Program by declaring three Matrices (2D Arrays). They are X matrix, Y matrix, and Z Matrix. The max number of rows and columns in the array are 100 ( change this if you need to use larger arrays). We can also use a Macro or Constant to store the 100 value.
  2. Prompt the user to provide the desired Row size and Column Size, and store them in the variables rows and columns respectively.
  3. Check for array bounds using the (rows >= 100 || rows <= 0 || columns >= 100|| columns <= 0) condition, And display an error message if the row/column sizeis beyond the present limits.
  4. 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
  5. 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
  6. Repeat the step-5 to Take the Second Matrix ( Matrix-Y) elements from the user.
  7. To Calculate the Addition of Two Matrices, We again need to use two nested For loops to iterate over the matrix elements.
  8. 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++)
      • Add the X[i][j] element with the Y[i][j] and store the result in Z[i][j]
      • which is equal to Z[i][j] = X[i][j] + Y[i][j];
  9. Once the above step-9 is finished, The Matrix-Z contains the Sum of Matrix-X and Matrix-Y.
  10. Display the Results( Maxtrix-Z) using another Two For loops.
  11. 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]);
  12. Stop the Program.

Program for Addition of Two Matrices in C Language using Loops:

Here is the program to Add Two Matrices in C programming language.

Program Output:

Let’s Compile and Run the program using GCC compiler (Any Compiler)

Compile the Program

$ gcc add-two-matrices.c

Test Case 1: Normal Case:

Run the program and Provide the Matrix-X and Matrix-Y elements.

addition-of-two-matrices-in-c-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 Sum of Two Matrices on the console.

Let’s look at a few more examples

Test 2: Negative cases:

Enter the invalid row and column sizes

As excepted, The program is displaying the error message if the user enters Invalid Sizes ( Present Limits are 1-100).

Program to perform the Addition of Two Matrices in C using Functions:

In the above program, We have used only a single function to Read the matrix, Display the Matrix, and Calculate the sum of two matrices. So let’s divide the above monolith into smaller functions so that the program becomes clean and elegant.

Here is the rewritten version of the above program, Where we defined three extra functions (except the main() function).

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
    • Prototype of readMatrix function – void readMatrix(int rows, int columns, int A[rows][columns])
    • The readMatrix() function takes three formal arguments which are rows, columns, and 2D 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 addMatrices() function – This is the function where we actually perform the addition of the Matrix-X and Matrix-Y
    • Prototype – void addMatrices(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 addition and stores the results in the Matrix-Z – Z[i][j] = X[i][j] + Y[i][j];

Program Output:

Compile and Run the Program.

Test 1:

addition-of-two-matrices-using-functions-in-c-program-output

Let’s try a few more examples and observe the output

Test 2: Negative Tests:

As we can see from the above output, The program is properly calculating the sum of two matrices and displaying the error message whenever the row/column sizes go out of the present limits.

Related Array 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 Add Two Matrices […]

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

Leave a Reply