Beruflich Dokumente
Kultur Dokumente
PROGRAM NEWTON
IMPLICIT NONE
REAL A ! number to be square-rooted
REAL X ! current value of root
INTEGER N ! loop counter
PROGRAM NEWTON
IMPLICIT NONE
REAL A ! number to be square-rooted
REAL X, XOLD ! current and previous value
REAL CHANGE ! change during one iteration
REAL, PARAMETER :: TOLERANCE = 1.0E-6 ! tolerance for convergence
DO
XOLD = X ! store previous value
X = 0.5 * ( X + A / X ) ! update value
PRINT *, X
PROGRAM NEWTON
IMPLICIT NONE
REAL A ! number to be square-rooted
REAL X, XOLD ! current and previous value
REAL CHANGE ! change during one iteration
REAL, PARAMETER :: TOLERANCE = 1.0E-6 ! tolerance for convergence
x2 x3
exp( x) = 1 + x + + +L
2! 3!
Note that each term is not worked out from scratch, but – more efficiently – as a multiple of
the previous one:
xn x x n −1
= ×
n! n (n − 1)!
PROGRAM POWER_SERIES
IMPLICIT NONE
REAL, EXTERNAL :: NEW_EXP ! declare a function to be used
REAL VALUE ! number to test
!=========================================================================
! First term
N = 0; TERM = 1; NEW_EXP = TERM
PROGRAM EXAM
IMPLICIT NONE
INTEGER MARK
CHARACTER GRADE
DO
WRITE( *, '("Enter mark (negative to end): ")', ADVANCE = 'NO' )
READ *, MARK
IF ( MARK < 0 ) STOP ! stop program with a negative value
PROGRAM EXAM
IMPLICIT NONE
INTEGER MARK
CHARACTER GRADE
DO
WRITE( *, '("Enter mark (negative to end): ")', ADVANCE = 'NO' )
READ *, MARK
IF ( MARK < 0 ) STOP ! stop program with a negative value
PROGRAM MATRIX
IMPLICIT NONE
REAL, DIMENSION(3,3) :: A, B, C ! declare size of A, B and C
! REAL A(3,3), B(3,3), C(3,3) ! alternative dimension statement
REAL PI ! the number pi
INTEGER I, J ! counters
CHARACTER (LEN=*), PARAMETER :: FMT = '( A, 3(/, 3(1X, F8.3)), / )'
! format string for output
! Matrix sum
C = A + B
WRITE( *, FMT ) 'A+B', ( ( C(I,J), J = 1, 3 ), I = 1, 3 )
! "Element-by-element" multiplication
C = A * B
WRITE( *, FMT ) 'A*B', ( ( C(I,J), J = 1, 3 ), I = 1, 3 )
Consider a function
sumsqr(n) = 12 + 2 2 + L + n 2
(This could be worked out analytically, but the intention is to illustrate loops.)
Fortran
Integer Function sumsqr( n )
Integer n ! declare argument type
Integer i ! declare internal variables
Do i = 1, n ! start of loop
sumsqr = sumsqr + i * i ! add to sum
End Do ! end of loop
Visual Basic
Function sumsqr(n As Integer) As Integer
Dim i As Integer ' declare internal variables
End Function
C++
int sumsqr( int n ) {
int i, value; // declare internal variables
return value;
}
Actually, the last is a little bit naughty (but typical of C++ shorthand):
i++ is equivalent to i = i + 1
value += i * i is equivalent to value = value + i * i