Home / Programs / Write a program that uses a function to perform addition and subtraction of two matrices containing integer numbers.
Programming Example

Write a program that uses a function to perform addition and subtraction of two matrices containing integer numbers.

👁 903 Views
💻 Practical Program
📘 Step by Step Learning
Write a program that uses a function to perform addition and subtraction of two matrices containing integer numbers.

Program 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++) /** Read first matrix elements **/
		for(j=0; j<col; j++)
			scanf("%d",&a[i][j]);
	printf("\n Enter the elements of the second matrix.\n");
	for(i=0; i<row; i++) /** Read second matrix elements **/
		for(j=0; j<col; j++)
			scanf("%d",&b[i][j]);
	mat_arith(a,b); /** function call **/

}
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];
			else if(choice==2)
					c[i][j]= a[i][j] - b[i][j];
				 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]);
		printf("\n\n ");
	}
	return;
}

Output


 Enter the elements of the first matrix.
1 2 3
1 2 3

 Enter the elements of the second matrix.
3 2 1
3 2 1

 For addition enter: 1
 For subtraction enter: 2

Enter your choice: 1

 The resulting matrix is:
 4 4 4

 4 4 4


Explanation

None

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.