C Program to Subtract Two Matrices

In this source code example, we will write a C program to subtract two matrices using a two-dimensional array.



C Program to Subtract Two Matrices

/* C Program to Subtract Two Matrices */

#include<stdio.h>

int main() {
	int i, j, rows, columns, a[10][10], b[10][10];
	int Subtraction[10][10];

	printf("\n Enter Number of rows and columns  :  ");
	scanf("%d %d", &i, &j);

	printf("\n Enter the First Matrix Elements\n");
	for (rows = 0; rows < i; rows++) {
		for (columns = 0; columns < j; columns++) {
			scanf("%d", &a[rows][columns]);
		}
	}

	printf("\n Enter the Second Matrix Elements\n");
	for (rows = 0; rows < i; rows++) {
		for (columns = 0; columns < j; columns++) {
			scanf("%d", &b[rows][columns]);
		}
	}

	for (rows = 0; rows < i; rows++) {
		for (columns = 0; columns < j; columns++) {
			Subtraction[rows][columns] = a[rows][columns] - b[rows][columns];
		}
	}

	printf("\n First Matrix A:\n");
	for (rows = 0; rows < i; rows++) {
		for (columns = 0; columns < j; columns++) {
			printf("%d \t ", a[rows][columns]);
		}
		printf("\n");
	}

	printf("\n Second Matrix: \n");
	for (rows = 0; rows < i; rows++) {
		for (columns = 0; columns < j; columns++) {
			printf("%d \t ", b[rows][columns]);
		}
		printf("\n");
	}

	printf("\n After Subtracting Matrix A from Matrix B = A - B \n");
	for (rows = 0; rows < i; rows++) {
		for (columns = 0; columns < j; columns++) {
			printf("%d \t ", Subtraction[rows][columns]);
		}
		printf("\n");
	}
	return 0;
}

Output:


 Enter Number of rows and columns  :  
2
2

 Enter the First Matrix Elements
9
8
7
6

 Enter the Second Matrix Elements
1
2
3
4

 First Matrix A:
9 	 8 	 
7 	 6 	 

 Second Matrix: 
1 	 2 	 
3 	 4 	 

 After Subtracting Matrix A from Matrix B = A - B 
8 	 6 	 
4 	 2 	 




Comments