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

C Programming Language Function in C Language (Article) Function in C Language (Program)

802

Program:

#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

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.