C program for matrix addition and subtraction

      This program reads two matrices and then computes either Matrix addition or subtraction of two matrices depending on the user choice.

matrix addition and subtraction program in c



Source Code :

#include<stdio.h>
#define row 2
#define col 3

void mat_arith(int [][col], int [][col]); /* function prototype */

int main()
{
	int a[row][col], b[row][col],i,j;
	printf("\n Enter the elements of the first matrix.\n");
	for(i=0; i < row; i++) 
		for(j=0; j < col; j++)
			scanf("%d",&a[i][j]);                   // Step 1
	printf("\n Enter the elements of the second matrix.\n");    
	for(i=0; i < row; i++) 
		for(j=0; j < col; j++)
			scanf("%d",&b[i][j]);                  // Step 2
	mat_arith(a,b); 

}
void mat_arith(int a[][col], int b[][col])
{
	int c[row][col],i,j,choice;
	printf("\n For addition enter: 1 \n For subtraction enter: 2\n");
	printf("\nEnter your choice: ");
	scanf("%d",&choice);
	for(i=0; i < row; i++)
		for(j=0; j < col; j++)
		{
			if(choice==1)
				c[i][j]= a[i][j] + b[i][j];           // Step 3
			else if(choice==2)
					c[i][j]= a[i][j] - b[i][j];   // Step 4
				 else
				{
				    printf("\n Invalid choice. Task not done.");
			            return;
				}
		}
	printf("\n The resulting matrix is:\n ");
	for(i=0; i < row; i++)
	{ 
		for(j=0; j < col; j++)
			printf("%d ", c[i][j]);          // Step 5
		printf("\n\n ");
	}
	return;
}


edit-code-image

Sample Test cases:

1.  Enter the elements of the first matrix.
    10
    15
    34
    56
    23
    32
Enter the elements of the second matrix.
    42
    21
    37
    43
    5
    11
For addition enter: 1
For subtraction enter: 2
Enter your choice: 1
The resulting matrix is:
 52 36 71
 
 99 28 43

2.  Enter the elements of the first matrix.
   15
   14
   23
   56
   32
   14
   Enter the elements of the second matrix.
   3
   15
   22
   43
   54
   23
  For addition enter: 1
  For subtraction enter: 2
  Enter your choice: 2
  The resulting matrix is:
 12 -1 1
 
 13 -22 -9

Explanation:

Step 1: The first matrix is read from the user using scanf() function.

Step 2: Similarly the second matrix is read from the user using scanf() function.

Step 3: If user prefers addition then matrix addition is computed.

Step 4: Otherwise matrix subtraction is computed.

Step 5: The resulting matrix is printed to output screen using printf() fucntion.

More Insights:

1. More about matrix computations

More Content:Explore More