Fortran/Fortran simple input and output

C. PROGRAM TO EVALUATE SUM OF FINITE SERIES

    WRITE(*,*)'ENTER THE VALUE OF X'
    READ(*,*)X              
    WRITE(*,*)'ENTER THE VALUE OF N'
    READ(*,*)N
    SUM=0.0
    DO 10I=1,N
    TERM=((-1)**I)*(X**(I*0.5))/I*(I+1))
    SUM=SUM+TERM
10  CONTINUE
    WRITE (*,*)`SUM OF SERIES'=,SUM
    PAUSE
    STOP
    END

Default output

edit

A Fortran program reads from standard input or from a file using the read statement, and it can write to standard output using the print statement. With the write statement one can write to standard output or to a file. Before writing to a file, the file must be opened and assigned a unit number with which the programmer may reference the file. If one wishes to use the write statement to write a statement to the default output, the syntax is write(*,*). It is used as follows:

program hello_world
    implicit none
    write (*,*) "Hello World!"
end program

This code writes "Hello World!" to the default output (usually standard output, the screen), similar to if one had used the print *, statement.

File output

edit

As a demonstration of file output, the following program reads two integers from the keyboard and writes them and their product to an output file:

program xproduct
    implicit none
    integer :: i, j
    integer, parameter :: out_unit=20

    print *, "enter two integers"
    read (*,*) i,j

    open (unit=out_unit,file="results.txt",action="write",status="replace")
    write (out_unit,*) "The product of", i, " and", j
    write (out_unit,*) "is", i*j
    close (out_unit)
end program xproduct

The file "results.txt" will contain these lines:

 The product of 2 and 3
 is 6

Each print or write statement on a new line by default starts printing on a new line. For example:

program hello_world
    implicit none

    print *, "Hello"
    print *, "World!"
end program

Prints, to standard output:

Hello
World!

If one had put "Hello World!" in one print statement, the text "Hello World!" would have appeared on one line.