# Coding Question 4 Free Section

## Matrix Multiplication Program

### C

```#include <stdio.h>

int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];

printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");

for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);

if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");

for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);

for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

printf("Product of the matrices:\n");

for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);

printf("\n");
}
}

return 0;
}```

### Java

``````public class MultiplyMatrices {

public static void main(String[] args) {
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

// Mutliplying Two matrices
int[][] product = new int[r1][c2];
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}

// Displaying the result
System.out.println("Sum of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
System.out.print(column + "    ");
}
System.out.println();
}
}
}``````

### One comment on “Coding Question 4 Free Section”

• Shubhrajit Dey

import java.util.*;
public class MatrixMultiplication{
static void matrixmul(int A[][],int B[][],int C[][],int r1,int c1,int r2,int c2){
for(int i=0;i<r1;i++){
for(int j=0;j<c2;j++){
for(int k=0;k<c1;k++){
C[i][j]+=A[i][k]*B[k][j];
}
}
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter r1 & c1 for A matrix :");
int r1=sc.nextInt();
int c1=sc.nextInt();
System.out.println("Enter r2 & c2 for B matrix :");
int r2=sc.nextInt();
int c2=sc.nextInt();
int A[][]=new int[r1][c1];
int B[][]=new int[r2][c2];
int C[][]=new int[r1][c2];
if(c1==r2){
System.out.println("Enter the element of A matrix");
for(int i=0;i<r1;i++){
for(int j=0;j<c1;j++){
A[i][j]=sc.nextInt();
}
}
System.out.println("Enter the element of B matrix");
for(int i=0;i<r2;i++){
for(int j=0;j<c2;j++){
B[i][j]=sc.nextInt();
}
}
matrixmul(A,B,C,r1,c1,r2,c2);
System.out.println("The result of matrix multiplicAation is :");
for(int i=0;i<r1;i++){
for(int j=0;j<c2;j++){
System.out.printf("%4d",C[i][j]);
}
System.out.println();
}
}
else{
System.out.println("Multiplication not possible");
}

}
}