Write a Fortran program that asks the user for the name of a data file. It then
ID: 658056 • Letter: W
Question
Write a Fortran program that asks the user for the name of a data file.
It then opens the file and reads the first line which will be the dimensions of the first two dimensional array to be read. it then dynamically allocates the matrix. it then reads the matrix one row per line. it then prints out the array row by row. it then repeats these steps for the second matrix. if the matrices can be added it will add them and print out the resulting matrix to the screen. if the matrices cannot be added it will see if they can be multiplied. if the matrices can be multiplied it will multipy them and display the resulting matrix. if it also cannot be multiplied, it will display a message saying these matrices cannot be either added or multiplied.
Explanation / Answer
Comments added
program mat_add_multiply
integer rowA, colA, rowB, colB, m, n
real A(100,100)
real B(100,100)
real C(100,100)
character operation, inputA*30, inputB*30
! reading operation from user
WRITE(*,*) "Enter operation either + or *"
Read (*,*) operation
! Reading name to open file
WRITE(*,*) ""
WRITE(*,*) ""
WRITE(*,*) "enter file name first matrix"
Read (*,*) inputA
OPEN (UNIT=20, file=inputA, STATUS='OLD')
! Read dimension of matrix A
READ (20,*) rowA,colA
! Read each matrix(array) elements
WRITE (*,*) "The 1st matrix is "
Do m= 1,rowA
READ (20,*) (A(m,n),n=1,colA)
write(*,"(100F7.2,$)") (A(m,n),n=1,colA)
End do
close (20)
! read file name
WRITE(*,*) ""
WRITE(*,*) ""
WRITE(*,*) "enter file name second matrix"
Read (*,*) inputB
OPEN (UNIT=30, file=inputB, STATUS='OLD')
! Read dimension of matrix A
READ (30,*) rowB,colB
! Read each matrix(array) elements
WRITE (*,*) "The 2nd matrix is "
Do m= 1,rowB
READ (30,*) (B(m,m),m=1,colB)
write(*,"(100F7.2,$)") (B(m,m),n=1,colB)
End do
close (30)
WRITE(*,*) ""
WRITE(*,*) ""
WRITE(*,*) "Result:"
WRITE(*,*) ""
If (operation == '*') then
if (colA.NE.rowB) then
write(*,*) "A*B cannot be done;"
write(*,*) " check matrices dimensions"
else
C = matmul(A(1:rowA,1:colA),B(1:rowB,1:colB))
Do n= 1,rowA
WRITE(*,'(100F7.2)') (C(m,n),n=1,colB)
End do
end if
else if (operation == '+') then
if (rowA.NE.rowB.or.colA.NE.colB) then
write(*,*) "A+B cannot be performed;"
write(*,*) "check matrices dimensions"
else
C = A(1:rowA,1:colA)+B(1:rowB,1:colB)
Do m= 1,rowA
WRITE(*,'(100F7.2)') (C(m,n),j=1,colB)
End do
end if
end if
END PROGRAM MAT_add_multiply
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.