laazyboy13
laazyboy13

Reputation: 11

Fortran Matrix Generation Code Error

This fortran code is supposed to copy data from a simple matrix table in a txt file, and then calculate the grade and average based upon the previous grades for each row and column. For some reason, I cannot get the grade nor the averages to print out, they appear blank or with 0's or stars. The program crashes upon running after it prints the matrix table from the txt file, it says the error is a access violation - soo not much help at all. Heres my code so far:

program calculate1
real,dimension(:,:),allocatable :: a
character(200)::line
print *,'How many rows are there?'
read *,n !amount of rows
print *,'How many columns are there?'
read *,m !amount of columns
allocate (a(n+1,m+1))
open(1, file='in1.txt')
call print_out (a,n+1,m+1)
Close(1);

contains
subroutine print_out(b,n,m)
real,dimension(:,:):: b
character(200)::line(n)
character(1)::g
write(*,'(10x)',advance='no')
do j=2,m-1
write(*,100,advance='no'),'hw',j-1
enddo
100 format(a2,i2,3x)
print '(a6,a6)','exam  ','grade  '
do i=1,n-1 !makes rows from data
read(1,'(a)') line(i)  !read from in1.txt
write(*,'(a)') line(i) !write to screen
enddo
do i=1,n         !makes (m+1)th column
b(i,m+1)= sum(b(i,1:m-1))+3*b(i,m)
enddo
do j=1,m+1             !makes (n+1)th row
b(n+1,j)= sum(b(1:n,j))/n
enddo
101 format(a8,4x,20f8.2)  ! format for average print
print 101, 'averages', b(n+1,j)
endsubroutine
endprogram 

and here is what is in the in1.txt file:

jackson     4.    4.    4.2   8.
johnson     4.    2.    2.11  3.
sugimoto    1.    0.    1.5   0.
wong        3.5   3.    3.    2.    

Upvotes: 1

Views: 285

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78354

Since this is homework I can only hint: your code reads a line from the file into a character variable and ignores it. It then does some operations on a matrix, b, which has not been assigned any values. Fortran programs often crash if provided the wrong type of variable in a write statement, for example a character variable when a format statement specifies a real number.

Since this is homework:

  • always use IMPLICIT NONE;
  • indentation will make your code easier to read, and easier for SO to help with;
  • your matrix sums, using loops, can be much more readily programmed using Fortran's array syntax; if you're learning to program in Fortran, learn the array syntax;
  • avoid global variables and magic numbers, your code has at least one of these.

Upvotes: 5

Related Questions