Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS151 / KCS251 Programming for Problem Solving - Using C Language
Lab Exercises
29. Write a program to print the multiplication of two N*N (Square) matrix.
/*
File: Prgrm29.c
Author: Aditya Saini
Date: Jan 18, 2021
Description: Program to print the multiplication of two N*N (Square) matrix.
*/
#include <stdio.h>
int main (void)
{
int mat_1[20][20], mat_2[20][20], m_mat[20][20];
int size;
int i, j, k;
//Input row and column
printf ("Input no of rows or columns: ");
scanf ("%d", &size);
//Input first matrix
printf ("\n***Input first matrix***\n");
for (i = 0; i <= size - 1; i++)
for (j = 0; j <= size - 1; j++)
{
printf ("Input element %d, %d: ", i + 1, j + 1);
scanf ("%d", &mat_1[i][j]);
}
//Input second matrix
printf ("\n***Input second matrix***\n");
for (i = 0; i <= size - 1; i++)
for (j = 0; j <= size - 1; j++)
{
printf ("Input element %d, %d: ", i + 1, j + 1);
scanf ("%d", &mat_2[i][j]);
}
//Calculate multiplication of matrices
for (i = 0; i <= size - 1; i++)
for (j = 0; j <= size - 1; j++)
{
m_mat[i][j] = 0;
for (k = 0; k <= size - 1; k++ )
m_mat[i][j] = m_mat[i][j] + mat_1[i][k] * mat_2[k][j];
}
//Print first matrix
printf ("\n***First Matrix***\n");
for (i = 0; i <= size - 1; i++)
{
for (j = 0; j <= size - 1; j++)
printf ("%d\t", mat_1[i][j]);
printf ("\n");
}
//Print second matrix
printf ("\n***Second Matrix***\n");
for (i = 0; i <= size - 1; i++)
{
for (j = 0; j <= size - 1; j++)
printf ("%d\t", mat_2[i][j]);
printf ("\n");
}
//Print multiplication of matrices
printf ("\n***Multiplication of Matrices***\n");
for (i = 0; i <= size - 1; i++)
{
for (j = 0; j <= size - 1; j++)
printf ("%d\t", m_mat[i][j]);
printf ("\n");
}
};
Output
Input no of rows or columns: 3
***Input first matrix***
Input element 1, 1: 5
Input element 1, 2: 6
Input element 1, 3: 1
Input element 2, 1: 2
Input element 2, 2: 4
Input element 2, 3: 8
Input element 3, 1: 3
Input element 3, 2: 7
Input element 3, 3: 9
***Input second matrix***
Input element 1, 1: 9
Input element 1, 2: 4
Input element 1, 3: 7
Input element 2, 1: 3
Input element 2, 2: 8
Input element 2, 3: 5
Input element 3, 1: 1
Input element 3, 2: 6
Input element 3, 3: 2
***First Matrix***
5 6 1
2 4 8
3 7 9
***Second Matrix***
9 4 7
3 8 5
1 6 2
***Multiplication of Matrices***
64 74 67
38 88 50
57 122 74
No comments:
Post a Comment
Please do not post spam links.