Skip to main content

Add and subtract matrices in FORTRAN

Short answer

Read rows, columns, and matrices using nested implied DO. Compute sum S(i,j)=A(i,j)+B(i,j) and difference D(i,j)=A(i,j)-B(i,j) in loops. Display each matrix row by row with FORMAT. For A=[1 2;3 4], B=[5 6;7 8], sum is [6 8;10 12] and difference [-4 -4;-4 -4].

Write a FORTRAN program to add and subtract two matrices and display the results in matrix form.

Method. Matrices of the same order r × c are read row by row with a nested implied DO. The sum is S(i,j) = A(i,j) + B(i,j) and the difference is D(i,j) = A(i,j) − B(i,j). Each result is printed one row per line using a FORMAT statement.

      PROGRAM MATADS
      INTEGER A(10,10), B(10,10), S(10,10), D(10,10)
      INTEGER R, C, I, J
      PRINT *, 'ENTER ROWS AND COLUMNS'
      READ *, R, C
      PRINT *, 'ENTER FIRST MATRIX'
      READ *, ((A(I,J), J = 1, C), I = 1, R)
      PRINT *, 'ENTER SECOND MATRIX'
      READ *, ((B(I,J), J = 1, C), I = 1, R)
      DO 20 I = 1, R
         DO 10 J = 1, C
            S(I,J) = A(I,J) + B(I,J)
            D(I,J) = A(I,J) - B(I,J)
   10    CONTINUE
   20 CONTINUE
      PRINT *, 'SUM OF THE MATRICES'
      DO 30 I = 1, R
         WRITE(*,100) (S(I,J), J = 1, C)
   30 CONTINUE
      PRINT *, 'DIFFERENCE OF THE MATRICES'
      DO 40 I = 1, R
         WRITE(*,100) (D(I,J), J = 1, C)
   40 CONTINUE
  100 FORMAT(10I5)
      STOP
      END

Sample: for A = [1 2; 3 4] and B = [5 6; 7 8], the sum is [6 8; 10 12] and the difference is [-4 -4; -4 -4]. Note that in READ *, ((A(I,J), J=1,C), I=1,R) the elements are typed row by row.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 11 questions →