C Program For Matrix Addition and Subtraction

In this C program, We will show “How to do Matrix Addition and Subtraction” with easy logic. So, let’s do it …

Matrix Addition and Subtraction

//C program to print a 2D Array using for loop taking user input.

//Here 'i' and 'j' means the rows and columns of the Matrix.
#include<stdio.h>
int main()
{
  int i, j, numberOfrows, numberOfcols;
  int A[10][10], B[10][10], C[10][10];

  printf("Enter the number of rows and cols: ");
  scanf("%d %d", &numberOfrows, &numberOfcols);

//Scanning the value of A Matrix.
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      printf("Enter The Elements of A[%d][%d] = ", i, j);
      scanf("%d", &A[i][j]);
    }
    printf("\n");
  }

//Scanning the value of B Matrix.
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      printf("Enter The Elements of B[%d][%d] = ", i, j);
      scanf("%d", &B[i][j]);
    }
    printf("\n");
  }



//Printing The Value of A Matrix.
  printf("The A Matrix is: ");
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      printf("%d ", A[i][j]);
    }
    printf("\n \t \t ");
  }

  printf("\n");


//Printing The Value of B Matrix.
  printf("The B Matrix is: ");
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      printf("%d ", B[i][j]);
    }
    printf("\n \t \t ");
  }



//Adding A and B Matrix.
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      C[i][j] = A[i][j] + B[i][j];
    }
    printf("\n");
  }

//Printing The Value of (A + B) Matrix.
  printf("The (A + B) Matrix is: ");
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      printf("%d ", C[i][j]);
    }
    printf("\n \t \t ");
  }

//Subtructing A and B Matrix.
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      C[i][j] = A[i][j] - B[i][j];
    }
    printf("\n");
  }

//Printing The Value of (A - B) Matrix.
  printf("The (A - B) Matrix is: ");
  for(i=0; i<numberOfrows; i++)
  {
    for(j=0; j<numberOfcols; j++)
    {
      printf("%d ", C[i][j]);
    }
    printf("\n \t \t ");
  }


return 0;
}

Keep learning with PrologiCode.

Leave a Comment