Skip to main content

Sum of two matrices in FORTRAN

Short answer

Read the order and both matrices using nested implied DO. Add corresponding elements: S(i,j)=A(i,j)+B(i,j). Print the sum row by row with FORMAT.

Write a program in FORTRAN to read two matrices from user, find their sum and display the sum.

Method. Read the order (rows R, columns C), then read both matrices with a nested implied DO (the inner variable J varies fastest, so the data is entered row by row). The two matrices must have the same order. Add corresponding elements in nested DO loops and display the sum, one row per line.

      PROGRAM MATSUM
      INTEGER A(10,10), B(10,10), S(10,10)
      INTEGER R, C, I, J
      PRINT *, 'ENTER NUMBER OF ROWS AND COLUMNS'
      READ *, R, C
      PRINT *, 'ENTER ELEMENTS OF FIRST MATRIX'
      READ *, ((A(I,J), J = 1, C), I = 1, R)
      PRINT *, 'ENTER ELEMENTS OF 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)
   10    CONTINUE
   20 CONTINUE
      PRINT *, 'SUM OF THE TWO MATRICES'
      DO 30 I = 1, R
         WRITE(*,100) (S(I,J), J = 1, C)
   30 CONTINUE
  100 FORMAT(10I6)
      STOP
      END

Sample: A = [1 2 3; 4 5 6], B = [6 5 4; 3 2 1] gives

     7     7     7
     7     7     7

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 11 questions →