Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

c program to read 2 matrices and display the multiplication matrix

c of them
real,allocatable,dimension(:,:)::A,B,C
integer row_a,col_a,row_b,col_b,row_c,col_c,i,j,k,l,ele_sum
print*,"program to multiply 2 matrices"
print*,"let, first matrix is A and second matrix is B"
print*,"enter the no of rows for A"
read*,row_a
print*,"enter the no of columns for A"
read*,col_a
print*,"enter the no of rows for B"
read*,row_b
print*,"enter the no of columns for B"
read*,col_b
allocate(A(row_a,col_a))
allocate(B(row_b,col_b))
if(col_a==row_b)then
print*,"the matrix multiplication AB is possible"
row_c=row_a
col_c=col_b
allocate(C(row_c,col_c))
print*,"enter the values of A column-wise"
read*,((A(i,j),i=1,row_a),j=1,col_a)
print*,"enter the values of B column-wise"
read*,((B(i,j),i=1,row_b),j=1,col_b)
do i=1,row_c
do j=1,col_c
C(i,j)=0
end do
end do
do k=1,row_c
do i=1,col_b
do j=1,col_a
C(k,i)=C(k,i)+A(k,j)*B(j,i)
end do
end do
end do
print*,"the result is AB-"
do k=1,row_c
print*,(C(k,l),l=1,col_c)
end do

else if(col_b==row_a)then
print*,"the matrix multiplication BA is possible"
row_c=row_b
col_c=col_a
allocate(C(row_c,col_c))
print*,"enter the values of A column-wise"
read*,((A(i,j),i=1,row_a),j=1,col_a)
print*,"enter the values of B column-wise"
read*,((B(i,j),i=1,row_b),j=1,col_b)
do i=1,row_c
do j=1,col_c
C(i,j)=0
end do
end do
do k=1,row_c
do i=1,col_a
do j=1,col_b
C(k,i)=C(k,i)+B(k,j)*A(j,i)
end do
end do
end do
print*,"the result is BA-"
do k=1,row_c
print*,(C(k,l),l=1,col_c)
end do

else
print*,"the multiplication is not possible"
end if
stop
end

You might also like