Computational Physics - Department of Physics

(Axel Boer) #1

2.1 Getting Started 11


Fortran C++
Program structure
PROGRAM something main ()
FUNCTION something(input) double (int) something(input)
SUBROUTINE something(inout)
Data type declarations
REAL (4) x, y float x, y;
REAL(8) :: x, y double x, y;
INTEGER :: x, y int x,y;
CHARACTER :: name char name;
REAL(8), DIMENSION(dim1,dim2) :: x double x[dim1][dim2];
INTEGER, DIMENSION(dim1,dim2) :: x int x[dim1][dim2];
LOGICAL :: x
TYPE name struct name {
declarations declarations;
END TYPE name }
POINTER :: a double (int) *a;
ALLOCATE new;
DEALLOCATE delete;
Logical statements and control structure
IF ( a == b) THEN if ( a == b)
b=0 { b=0;
ENDIF }
DO WHILE (logical statement) while (logical statement)
do something {do something
ENDDO }
IF ( a>=b ) THEN if ( a>=b)
b=0 { b=0;
ELSE else
a=0 a=0; }
ENDIF
SELECT CASE (variable) switch(variable)
CASE (variable=value1) {
do something case 1:
CASE (...) variable=value1;
... do something;
break;
END SELECT case 2:
do something; break;...
}
DO i=0, end, 1 for( i=0; i<=end; i++)
do something { do something ;
ENDDO }

Table 2.2Elements of programming syntax.


doubler, s; /declare variables/
r = atof(argv[1]);/convert the text argv[1] to double/
s = sin(r);
printf("Hello, World! sin(%g)=%g\n", r, s);
return0; /success execution of the program/
}


The compiler must see a declaration of a function before you can call it (the compiler
checks the argument and return types). The declaration of library functions appears in so-
called header files that must be included in the program, for example#include <stdlib.h.
We call three functionsatof, sin, printfand these are declared in three different
header files. The main program is a function called main with areturn value set to an integer,

Free download pdf