Posted on by Kalkicode
Code Matrix

Multiplication of two matrix in c

matrix multiplication formula

C program for Two Matrix Multiplication. Here mentioned other language solution.

// Include header file
#include <stdio.h>
#define ROW 3
#define COL 3
/*
  C program for
  Two matrix multiplication
*/
// Display the element of given 2d matrix
void printRecord(int matrix[][COL])
{
	printf("  --------------\n");
	// Iterate the row element
	for (int i = 0; i < ROW; i++)
	{
		// Iterate the column element
		for (int j = 0; j < COL; j++)
		{
			// Display element value
			printf("  %d", matrix[i][j]);
		}
		// Add new line
		printf("\n");
	}
	printf("\n");
}
void multiplication(int a[][COL], int b[][COL])
{
	// This matrix are store the result of multiplication 
	int result[ROW][COL];
	for (int i = 0; i < ROW; i++)
	{
		for (int j = 0; j < COL; j++)
		{
			// Set the initial value of new matrix element
			result[i][j] = 0;
			for (int k = 0; k < ROW; k++)
			{
				// Multiply matrix A [i] row and [k] columns to 
				// the Matrix B [k] columns and [j] rows.
				result[i][j] += a[i][k] * b[k][j];
			}
		}
	}
	printf("  Matrix A\n");
	// Print element of matrix x
	printRecord(a);
	printf("  Matrix B\n");
	// Print element of matrix y
	printRecord(b);
	printf("  Matrix [(A) x (B)]\n");
	// Display resultant matrix
	printRecord(result);
}
int main()
{
	// Define matrix A
	int a[][COL] = {
		{1 , 2 , 3} , 
      	{6 , 1 , 2} , 
      	{5 , 4 , 3}
	};
	// Define matrix B
	int b[][COL] = {
		{3 , 1 , 3} , 
      	{1 , 1 , 2} , 
      	{2 , 2 , 3}
	};
	multiplication(a, b);
	return 0;
}

Output

  Matrix A
  --------------
  1  2  3
  6  1  2
  5  4  3

  Matrix B
  --------------
  3  1  3
  1  1  2
  2  2  3

  Matrix [(A) x (B)]
  --------------
  11  9  16
  23  11  26
  25  15  32

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment