1 1 2 2 3
....5....0....5....0....5....0
6
35 70 52 83 98 68
12 76 35 24 9 27
46 49 53 57 15 29
66 87 25 40 93 21
100 65 77 88 4 51
83 12 19 54 7 100
Write a Fortran program that reads in this matrix and prints the upper triangular part. The upper triangular part of a square matrix consists of all entries on and above the diagonal.
1 1 2 2 3 3
....5....0....5....0....5....0....5
Input Matrix:
35 70 52 83 98 68
12 76 35 24 9 27
46 49 53 57 15 29
66 87 25 40 93 21
100 65 77 88 4 51
83 12 19 54 7 100
Upper Triangular Part:
35 70 52 83 98 68
76 35 24 9 27
53 57 15 29
40 93 21
4 51
100
PROGRAM UpperTriangularMatrix
IMPLICIT NONE
INTEGER, PARAMETER :: SIZE = 10
INTEGER, DIMENSION(1:SIZE,1:SIZE) :: Matrix
INTEGER :: Number
INTEGER :: Position
INTEGER :: i, j
CHARACTER(LEN=100) :: Format
READ(*,"(I5)") Number
DO i = 1, Number
READ(*,"(10I5)") (Matrix(i,j), j = 1, Number)
END DO
WRITE(*,"(1X,A)") "Input Matrix:"
DO i = 1, Number
WRITE(*,"(1X,10I5)") (Matrix(i,j), j = 1, Number)
END DO
WRITE(*,"(/1X,A)") "Upper Triangular Part:"
Position = 2
DO i = 1, Number
WRITE(Format,"(A,I2.2,A)") "(T", Position, ", 10I5)"
WRITE(*,Format) (Matrix(i,j), j = i, Number)
Position = Position + 5
END DO
END PROGRAM UpperTriangularMatrix
Click here to download this program.
1 1 2 2 3
....5....0....5....0....5....0
6
35 70 52 83 98 68
12 76 35 24 9 27
46 49 53 57 15 29
66 87 25 40 93 21
100 65 77 88 4 51
83 12 19 54 7 100
The output of the program is:
1 1 2 2 3 3
....5....0....5....0....5....0....5
Input Matrix:
35 70 52 83 98 68
12 76 35 24 9 27
46 49 53 57 15 29
66 87 25 40 93 21
100 65 77 88 4 51
83 12 19 54 7 100
Upper Triangular Part:
35 70 52 83 98 68
76 35 24 9 27
53 57 15 29
40 93 21
4 51
100
If we could find some way to fill in ??, we will have a good format. Note that not all I5s in 10I5 will be used. If a WRITE has fewer than 10 data values, the unused I5s will be ignored. See Scanning a Format: I for the details.(T??, 10I5)
Here, Position is an INTEGER variable whose initial value and step size are 2 and 5, respectively. Therefore, if the value of Position is 7, the above WRITE generates the following into CHARACTER variable Format:CHARACTER(LEN=100) :: Format WRITE(Format,"(A,I2.2,A)") "(T", Position, ", 10I5)"
Note that we use I2.2 rather than I2 because we do not want to have a space between T and 7.(T07, 10I5) ^^ || ++----- printed with I2.2