There is a file called mat2.txt. Write a Fortran program that does the following
ID: 3889947 • Letter: T
Question
There is a file called mat2.txt. Write a Fortran program that does the following:
• Declares a string variable (suggested length: at least 80 characters) to hold the input file name.
• Prompt the user for an input file name and read the user's input to your string variable.
• Declare a two-dimensional dynamic integer array. Hint: dimension(:,:), allocatable will be handy.
• Open the file name the user has entered for reading and read the first line to see how many lines and columns it has. Use that information to allocate your dynamic array. Use a loop to read the rest of the input file into your array. Close the input file.
• Use a separate loop to print the array to the console in a neat table. Noting that none of the numbers in the input file is larger than 99, choose an output format that results in a neat table with no more than 4 spaces before each number.*
Do not assume that the input file has a fixed number of rows or columns. Assume that that information is on the first line of the file and read it. Your program may be tested with a different file with a different number of rows and columns.
* Note that this will require some thought since the number of columns is can change and your code must adjust for that at runtime. There are several different ways to do this. Among them are creating the format string dynamically or using a nested loop to print one column at a time on an output line, using advance="no" in the written statement to keep printing on one line until you are done with it.
The mat2.txt looks like this
10, 5
75 82 48 49 95
74 69 44 95 54
39 31 64 34 13
65 95 70 58 14
17 3 75 22 25
70 43 27 75 84
3 38 67 25 25
27 76 65 50 81
4 79 16 69 24
9 18 11 89 92
Explanation / Answer
program inputoutput
implicit none
!declaration of variables for storing file name
Character(len=80) :: filename
!declaration for dyanmic arary
real, dimension (:,:), allocatable :: darray
!declaration for size x,y and for indices in loop i,j
integer :: x, y
integer :: i, j
Print *, "Input the filename"
!reading the inputed file name
read(*,*) filename
!opening the required file and giving it index 1 for readily use
open (1, file=filename)
!reading first two input for array size
do i=1,2
! read(1,*) x, y
end do
!allocating memory to dynamic array
allocate ( darray(x,y) )
!looping to store all ements in array from the required file
do i=1,x
do j=1,y
read(1,*) darray(i,j)
end do
end do
!closing the file
close(1)
!printing loop for array
do i = 1, x
do j = 1, y
print*, " ", darray(i,j)
end do
!printing a new line after every row
print*, "/"
end do
end program inputoutput
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.