0% found this document useful (0 votes)
19 views2 pages

Adding and Multiplying 2 Matrices

Uploaded by

Anish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views2 pages

Adding and Multiplying 2 Matrices

Uploaded by

Anish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

//Adding and multiplying 2 matrices and storing it in a new matrix

/*
In functions specifieng row size is optional but column size has to be specified.
But in main function the size has to be specified for both row and column.
*/

#include<stdio.h>
#include<stdlib.h>

void enter_value(int arr[][10], int m, int n)


{
printf("Enter array elements: \n");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
scanf("%d", &arr[i][j]);
}
}
}

void display(int arr[][10], int m, int n)


{
printf("\nArray elements: \n");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
}

void add_matrix(int a[][10], int b[][10], int c[][10], int m, int n)


{
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
c[i][j] = a[i][j] + b[i][j];
}
}
}

void mul_matrix(int a[][10], int b[][10], int c[][10], int m, int n, int p, int q)
{
int sum;
if(n != p){
printf("Invalid matrix for multiplication\n\a");
return;
}

for(int i = 0; i < m; i++){


for(int j = 0; j < q; j++){
sum = 0;
for(int k = 0; k < n; k++){
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
}

int main()
{
int a[10][10], b[10][10], c[10][10];
int m, n, p, q, choice;
printf("1.Add 2 matrix:\n");
printf("2.Multiply 2 matrix:\n\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice)
{
case 1:printf("Enter size of array(row and column): ");
scanf("%d%d", &m, &n);

enter_value(a, m, n);
enter_value(b, m, n);

add_matrix(a, b, c, m, n);

display(c, m, n);
break;

case 2:printf("Enter size of first array: ");


scanf("%d%d", &m, &n);
enter_value(a, m, n);

printf("Enter size of second array: ");


scanf("%d%d", &p, &q);
enter_value(b, p, q);

mul_matrix(a, b, c, m, n, p, q);

display(c, m, q);
break;

default:printf("Invalid choice!\n\a");
break;
}
}

You might also like