12.07.2015 Views

CAD in Civil Engineering - Baustatik-Info-Server

CAD in Civil Engineering - Baustatik-Info-Server

CAD in Civil Engineering - Baustatik-Info-Server

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Computer Languages for Eng<strong>in</strong>eersBook of Examples2013University of Duisburg-EssenFaculty of Eng<strong>in</strong>eer<strong>in</strong>gDepartment of <strong>Civil</strong> Eng<strong>in</strong>eer<strong>in</strong>gStructural Analysis and ConstructionDr. E. Baeck7.8.2013


Page iv Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.8.1 Explicit Loops with Counter <strong>in</strong> 66, 77 and 90+ . . . . . . . . . . . . . . . . . . 292.8.2 Simple Nested Loop Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 302.8.3 Quit a Cycle or a Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.8.4 Implicit, General Loop without a Control Structure <strong>in</strong> 90+ . . . . . . . . . . . . 322.8.5 Factorial <strong>in</strong> FORTRAN 90++ . . . . . . . . . . . . . . . . . . . . . . . . . . . 332.9 Branch<strong>in</strong>g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342.9.1 if Statement, Fortran 66 like . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342.9.2 Implementation of a Quadratic Equation Solver . . . . . . . . . . . . . . . . . . 352.9.2.1 Some Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352.9.2.2 A Flow-Chart of the QuadSolver . . . . . . . . . . . . . . . . . . . . 362.9.2.3 Quadratic Equation, Solver Implementation Fortran 66 like . . . . . . 362.9.2.4 Quadratic Equation, Solver Implementation Fortran 90 like . . . . . . 382.10 Subrout<strong>in</strong>es and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.10.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.10.2 Subrout<strong>in</strong>es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412.10.3 Functions as Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422.11 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422.11.1 Static Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422.11.2 Dynamical Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432.11.3 Automatic Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432.11.4 A little Array Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432.11.5 Pseudo Dynamic Arrays <strong>in</strong> Fortran 77 . . . . . . . . . . . . . . . . . . . . . . . 472.12 Global Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492.12.1 Classical Fortran and Common . . . . . . . . . . . . . . . . . . . . . . . . . . . 492.12.2 Some Aspects of the Module Concept of Fortran 90 . . . . . . . . . . . . . . . . 492.12.3 Us<strong>in</strong>g global Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503 Some Examples 533.1 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533.2 Simple Sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533.3 Calculation of real*4/8 Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543.4 Relative Precision with Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553.5 Newton’s Algorithm to calculate a Root . . . . . . . . . . . . . . . . . . . . . . . . . . 573.6 Matrix Product with 77-Ma<strong>in</strong> and 90-Library . . . . . . . . . . . . . . . . . . . . . . . 654 L<strong>in</strong>ear Algebra, Vectors and Matrices 694.1 Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694.1.1 Outl<strong>in</strong>es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694.1.2 Reset and List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694.1.3 LU-Extract, MatMult and DiffMat . . . . . . . . . . . . . . . . . . . . . . . . . 734.1.4 Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764.1.5 Memory Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784.1.6 Multi Matrix Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814.1.7 Trac<strong>in</strong>g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854.2 Gauss-LU-Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894.2.1 Gauss Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89E. Baeck


CONTENTSPage v4.2.2 Memory Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 904.2.3 LU-Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 924.2.4 Trac<strong>in</strong>g and Memory Po<strong>in</strong>ters . . . . . . . . . . . . . . . . . . . . . . . . . . . 954.2.4.1 Trac<strong>in</strong>g gaussLU . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954.2.4.2 Prepar<strong>in</strong>g Ma<strong>in</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 984.2.5 Gauss FB-Substitution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1014.2.6 L<strong>in</strong>are Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102II C/C++ 1075 Development Tools 1115.1 The Code::Blocks IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1116 Basics of C/C++ 1156.1 The Precompiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1156.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1166.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1166.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1176.4.1 Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1176.4.2 Arthmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1176.4.3 Compound Arithmetic Assignment . . . . . . . . . . . . . . . . . . . . . . . . 1176.4.4 Increment - Decrement Operators . . . . . . . . . . . . . . . . . . . . . . . . . 1176.4.5 Relational and Equality Operators . . . . . . . . . . . . . . . . . . . . . . . . . 1186.4.6 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1186.4.7 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1186.4.8 Compound Bitwise Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . 1196.4.9 Explicit Type Cast<strong>in</strong>g Operator . . . . . . . . . . . . . . . . . . . . . . . . . . 1196.4.10 sizeof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1196.4.11 Address and Value Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1206.5 Tak<strong>in</strong>g about the Hello . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1206.6 A For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1216.7 Static Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1236.8 Branch<strong>in</strong>g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1256.9 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1276.10 OOP with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1296.10.1 Some UML Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1296.10.2 C++ Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1306.10.2.1 Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1306.10.2.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1327 Profile Example 1337.1 Class Concept for the T<strong>in</strong>-Walled Approach . . . . . . . . . . . . . . . . . . . . . . . . 1337.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1337.2.1 Base, the Base Class of all Classes . . . . . . . . . . . . . . . . . . . . . . . . . 1357.2.2 Node Class for Model Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1377.2.3 Check<strong>in</strong>g the Node Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1397.8.2013


CONTENTS Page 17.2.4 Element Class for Model Elements . . . . . . . . . . . . . . . . . . . . . . . . . 1417.2.5 Check<strong>in</strong>g the Element Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1457.2.6 Profile Class for Model Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . 1477.2.7 Check<strong>in</strong>g the Profile Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1567.2.8 H-Profile Class for Model Profiles . . . . . . . . . . . . . . . . . . . . . . . . . 1597.2.9 Check<strong>in</strong>g the HProfile Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162III Appendix 165A The Console’s Friends 167A.1 Directory Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169A.1.1 Select<strong>in</strong>g a Drive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169A.1.2 List<strong>in</strong>g the Content of a Directory . . . . . . . . . . . . . . . . . . . . . . . . . 169A.1.3 Creat<strong>in</strong>g and Remov<strong>in</strong>g a Directory . . . . . . . . . . . . . . . . . . . . . . . . 170A.1.4 Brows<strong>in</strong>g through Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . 170A.2 File Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171A.3 Environment Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172B Code::Blocks’s first Project 173C Some Theory 181C.1 Section Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181C.1.1 The Area of a Profile Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181C.1.2 First Moments of an Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181C.1.3 Second Moments of an Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182C.1.4 Center of Mass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183C.1.5 Moments of Inertia with Respect to the Center of Mass . . . . . . . . . . . . . . 183C.1.6 Ma<strong>in</strong> Axis Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1847.8.2013


Page 2 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13E. Baeck


Part IFORTRAN3


1Development Tools1.1 The Development Toolcha<strong>in</strong>To develop a computer program there are three possible program types.• Interpreted ProgramsAn <strong>in</strong>terpreted program file is compiled, i.e. translated, <strong>in</strong>to mach<strong>in</strong>e code at run time. Thatmeans, that repeated statements are compiled not only ones. To execute a <strong>in</strong>terpreted program 1 thesource code is <strong>in</strong>terpreted, i.e. compiled, l<strong>in</strong>e by l<strong>in</strong>e by an <strong>in</strong>terpreter. A very simple <strong>in</strong>terpretedprogram is a batch statement <strong>in</strong> the console w<strong>in</strong>dow. The Basic language orig<strong>in</strong>ally was designedas an <strong>in</strong>terpreted language. The MS-Dos of the first years was shipp<strong>in</strong>g a Basic <strong>in</strong>terpretor asdevelopment tool. Today we know the Basic language as Visual Basic for Application mostlyfrom the MS software packages like MS Office.• Compiled ProgramsTo create a compiled program, also called executable, there are some steps necessary. Afterhav<strong>in</strong>g created the source files with an editor each of this source files has to be compiled bythe so-called compiler <strong>in</strong>to an object module. The object consists of b<strong>in</strong>ary native code, codewhich can be understood by the processor of the dest<strong>in</strong>ation platform. With<strong>in</strong> a second step allobject modules and the the used libraries are l<strong>in</strong>ked to an executable by the so-called l<strong>in</strong>ker. Thelibraries, especially the system libraries, are used to access the system resources like keyboard,screen and discs. This code is part of the develop system and can be used <strong>in</strong> an own applicationby l<strong>in</strong>k<strong>in</strong>g. If you are develop<strong>in</strong>g software for a w<strong>in</strong>dows system (MS-W<strong>in</strong>dow, X-W<strong>in</strong>dows, etc.)<strong>in</strong> an additional last step system resources are l<strong>in</strong>ked to the executable by an resource l<strong>in</strong>kder.Program languages which are used to build an native executable are for example FORTRAN, C,C++ 2 .• Programs runn<strong>in</strong>g on virtual mach<strong>in</strong>esLanguages which are designed for bytecode are compiled <strong>in</strong> an neutral format. This format is notdirectly runn<strong>in</strong>g an the processor. The compiled module can be executed on a real processor us<strong>in</strong>ga virtual mach<strong>in</strong>e, which translates the bytecode just <strong>in</strong> time before execut<strong>in</strong>g it. So bytecode may1 An <strong>in</strong>terpreted program often is called script.2 The languages C and C++ are very important, because the operat<strong>in</strong>g systems L<strong>in</strong>ux and W<strong>in</strong>dows are written <strong>in</strong> C, newparts of W<strong>in</strong>dows are written <strong>in</strong> C++ and C# too5


Page 6 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13often be either directly executed on a virtual mach<strong>in</strong>e (i.e. <strong>in</strong>terpreter), or it may be further compiled<strong>in</strong>to mach<strong>in</strong>e code for better performance. Languages which are designed for the executionof bytecode are Java, Smalltalk, Python, Forth, TCL and C#.1.2 Some History1.2.1 MotivationTo understand the importance of the development of the FORTRAN language, the code for the calculationof the nth fibunacci number is given <strong>in</strong> mach<strong>in</strong>e and assembler code.The fibunacci number are def<strong>in</strong>ed as follows.f n = f n−1 + f n−2 for n > 2, with f 0 = 1 and f 1 = 1 (1.1)The implementation of the calculation of the nth fibunacci numberis given below <strong>in</strong> mach<strong>in</strong>e code1 8B542408 83FA0077 06B80000 0000C3832 FA027706 B8010000 00C353BB 010000003 B9010000 008D0419 83FA0376 078BD98B4 C84AEBF1 5BC3The implementation of the calculation of the nth fibunacci numberis given below <strong>in</strong> x86 assembler.1 fib:2 mov edx, [esp+8]3 cmp edx, 04 ja @f5 mov eax, 06 ret78 @@:9 cmp edx, 210 ja @f11 mov eax, 112 ret1314 @@:15 push ebx16 mov ebx, 117 mov ecx, 11819 @@:20 lea eax, [ebx+ecx]21 cmp edx, 322 jbe @f23 mov ebx, ecx24 mov ecx, eax25 dec edx26 jmp @b2728 @@:29 pop ebx30 retE. Baeck


1.2. SOME HISTORY Page 71.2.2 FORTRAN’s HistoryThe first compiler was written by Grace Hopper, <strong>in</strong> 1952, for the A-0 System language, which today hasno relevance any more.The computer language FORTRAN (= FORmular TRANslator) was developed form IBM for the computerType 704 <strong>in</strong> 1954-1957 (see figure 1.1 3 ) and was the first computer language which was ableto handle mathematical formulas <strong>in</strong> nearly mathematical notation. In the time before FORTRAN onlymach<strong>in</strong>e code or assembler was available. Therefore FORTRAN is a very important milestone <strong>in</strong> programm<strong>in</strong>g.The computer Type 704 was able to perform 4000 <strong>in</strong>teger multiplicationsper second. A modern computer is able to performsome 100 millions of <strong>in</strong>teger multiplications.The 1st FORTRAN version was followed <strong>in</strong> 1958 by FOR-TRAN II. FORTRAN IV was published <strong>in</strong> 1962 and becameANSI-standard as FORTRAN 66.The next standardized version is called FORTRAN 77. TodayFORTRAN 77 is often used as computer language <strong>in</strong> eng<strong>in</strong>eer<strong>in</strong>g,especially <strong>in</strong> ad don software packages like ISML or NAG.Figure 1.1: IBM Type 704 [1]FORTRAN 90 was the next revision after FORTRAN 77. The concept of object orientated programm<strong>in</strong>g(OOP) was <strong>in</strong>troduced <strong>in</strong> the FORTRAN language as well as the usual more flexible free format. Furthermoredynamical memory management, build <strong>in</strong> matrix arithmetic and the possibility of recursivefunctions were implemented.With FORTRAN 95 the next revision was published. Obsolete constructs are removed and besides automaticdeallocation of arrays which go out of scope some new key words are <strong>in</strong>troduced.With FORTRAN 2003 a better <strong>in</strong>teroperability with the C programm<strong>in</strong>g language was <strong>in</strong>troduced. Abetter <strong>in</strong>tegration <strong>in</strong>to the host operat<strong>in</strong>g system is given (access to command l<strong>in</strong>e arguments and environmentvariables).The last revision is the revision FORTRAN 2008 which <strong>in</strong>troduces Co-Arrays, a parallel process<strong>in</strong>gmodel and the data type BIT.S<strong>in</strong>ce FORTRAN has been <strong>in</strong> use for more than fifty years, there is a vast body of FORTRAN <strong>in</strong> daily usethroughout the scientific and eng<strong>in</strong>eer<strong>in</strong>g communities. It is the primary language for some of the most<strong>in</strong>tensive supercomput<strong>in</strong>g tasks, such as weather and climate model<strong>in</strong>g, computational fluid dynamics,computational chemistry, computational economics, plant breed<strong>in</strong>g and computational physics. Eventoday, half a century later, many of the float<strong>in</strong>g-po<strong>in</strong>t benchmarks to gauge the performance of newcomputer processors are still written <strong>in</strong> FORTRAN (e.g., CFP2006, the float<strong>in</strong>g-po<strong>in</strong>t component of theSPEC CPU2006 benchmarks).3 Note: The programmer sitt<strong>in</strong>g <strong>in</strong> front of his operator panel is not the author <strong>in</strong> his young days.7.8.2013


Page 8 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 131.3 The Fixed FORTRAN Format and it’s RootsThe fixed FORTRAN format is a child ofthe punch<strong>in</strong>g cards time. Each l<strong>in</strong>e of codewas punched onto one card. You had topunch n cards for a source code with n l<strong>in</strong>esof code. To handle the cards <strong>in</strong> a batch, i.e.to avoid chaos <strong>in</strong> the order, the cards werenumbered <strong>in</strong> the last 8 columns (see figure1.2). Therefor <strong>in</strong> fixed FORTRAN formatthe last 8 columns of 80 available columns Figure 1.2: IBM FORTRAN Punch<strong>in</strong>g Cardare columns of comment. Their <strong>in</strong>formationis not considered <strong>in</strong> the compile step. The lead<strong>in</strong>g 5 columns are columns for label numbers andmust not used for statements. The column 6 is the column for the cont<strong>in</strong>uation l<strong>in</strong>e flag.A card punch (see figure 1.3) such as theIBM 3525 (not to be confused with keypunch),is an electronically mechanizedoutput device used to punch data <strong>in</strong>topunched cards. Sometimes comb<strong>in</strong>ed withcard readers and other functions to formmultifunction mach<strong>in</strong>es, such as the IBM2540 card reader-punch, such devices wereattached to a computer.If you look at the properties of a consolew<strong>in</strong>dow on W<strong>in</strong>dowsXP, you will f<strong>in</strong>d abuffer size per l<strong>in</strong>e for 80 characters asstandard. The 80 character l<strong>in</strong>e length resultsfrom the format of a punch card with it’s 80 columns.Figure 1.3: IBM Card PunchE. Baeck


1.4. SOME FREE FORTRAN TOOLS Page 91.4 Some free FORTRAN ToolsCommercial FORTRAN compilers are often expensive and there for we try to f<strong>in</strong>d an open source developmentpackage for our lecture. Fortunately there are many FORTRAN development tools available forfree <strong>in</strong> the Internet some of them are discussed below. If you use one of this packages it is recommendedto update it from the orig<strong>in</strong>al project site.• Watcom Fortran 77Open Watcom is a project of the open source community to ma<strong>in</strong>ta<strong>in</strong> and enhance the WatcomC, C++, and Fortran cross compilers and tools. An Open Source license from Sybase allows freecommercial and non-commercial use of Open Watcom. More <strong>in</strong>formation about Open Watcom’sfeatures, details about Open Watcom’s history and the supported platforms are given on the projectsite http://www.openwatcom.org/<strong>in</strong>dex.php.• M<strong>in</strong>GW PackageM<strong>in</strong>GW 4 provides a complete Open Source programm<strong>in</strong>g tool set which is suitable for the developmentof native MS-W<strong>in</strong>dows applications, and which do not depend on any 3rd-party C-RuntimeDLLs (only the Microsoft C runtime, MSVCRT). More <strong>in</strong>formations about M<strong>in</strong>GW are availableon the project page http://www.m<strong>in</strong>gw.org/.• G95 PackageG95 is based on the G77 of the M<strong>in</strong>GW package. G95 provides a FORTRAN compiler for theversions 77, 90, 95 and 2003. The extension of source file selects the FORTRAN version. More<strong>in</strong>formations about G95 are available on the project page http://g95.org/.• Code::BlocksCode::Blocks provides a cross-platform IDE for L<strong>in</strong>ux, Mac-OS and W<strong>in</strong>dows support<strong>in</strong>g a widthrange of available compilers and debuggers. More <strong>in</strong>formations about Code::Blocks are availableon the project site http://www.codeblocks.org.1.5 The Open Watcom Development SuiteThe first FORTRAN 77 compiler of the Watcom Suite was published <strong>in</strong> 1985 for the IBM PC. S<strong>in</strong>ce 2003the FORTRAN 77 and the C/C++ compilers are available as an open source project under Open Watcom.The Open Watcom IDE 5 consists of the follow<strong>in</strong>g three ma<strong>in</strong> modules.• IDE Project ManagerWith<strong>in</strong> the Project Manager application projects are <strong>in</strong>itialized. The application type is set. Sourcefiles are added to the project. Tools are started out of the manager application.• EditorThe Editor can be used to write source files for a project.4 M<strong>in</strong>imalist GNU for W<strong>in</strong>dows package is a port<strong>in</strong>g of the LINUX development tools.5 IDE means Integrated Development Environment.7.8.2013


Page 10 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13• DebuggerTo check an application the executable can be started with<strong>in</strong> a debugger program. The commonfeatures of a debugger are supported.The disadvantage of the Open Watcom suite is, that the three regarded components are not <strong>in</strong>tegratedwith<strong>in</strong> one application. Figure 1.4 shows the one and only source file of the famous hello world appliaction.Double click<strong>in</strong>g the source file <strong>in</strong> the manager will start the editor application (see figure 1.4).Figure 1.4: Watcom-IDE-ManagerIf standard FORTRAN 77 is used, format<strong>in</strong>g could be a problem, because Open Watcom 6 does not supportany format<strong>in</strong>g highlight<strong>in</strong>gs. So we use a format<strong>in</strong>g comment, which marks the first 7 columns of sourcel<strong>in</strong>e. You have to be careful too with the comment columns start<strong>in</strong>g with column 73. This commentcolumns also are not marked with<strong>in</strong> the cod<strong>in</strong>g.If the program sources are compiled, the l<strong>in</strong>ker creates the executable l<strong>in</strong>k<strong>in</strong>g the object files 7 with thelibraries. To check the executable the debugger can be started from the Watcom-IDE-Manager. Figure1.6 shows a debugger session to check our famous startup example hello world.6 Here we talk about the version 1.8.7 Object files are compiled source files, created by the compiler.E. Baeck


1.5. THE OPEN WATCOM DEVELOPMENT SUITE Page 11Figure 1.5: Watcom-Editor Session to write the hello worldFigure 1.6: Watcom-Debugger Session to check the hello world7.8.2013


Page 12 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 131.6 The M<strong>in</strong>GW PackageThe M<strong>in</strong>GW package is a port<strong>in</strong>g of the development tools which are by standard available on theL<strong>in</strong>ux/Unix platform. It’s no longer necessary to use a L<strong>in</strong>ux emulat<strong>in</strong>g layer like cygw<strong>in</strong> 8 . M<strong>in</strong>GWcontents above all compilers, a l<strong>in</strong>ker, a debugger and a make utility. There is no IDE available with<strong>in</strong>the M<strong>in</strong>GW package. That means if you want to use the pure M<strong>in</strong>GW package to develop applicationsyou have to start the tool-cha<strong>in</strong> manually. Because some of the tools are spawn<strong>in</strong>g other tools as helperapplication you have setup the correct path access to the M<strong>in</strong>GW b<strong>in</strong>ary folder.If we want to use the M<strong>in</strong>GW tools from the console w<strong>in</strong>dow, we have to setup the correct path access.This is shown <strong>in</strong> figure 1.7. The M<strong>in</strong>GW b<strong>in</strong>ary folder is cha<strong>in</strong>ed to the actual search path. There area lot of compiler options which are supported by the M<strong>in</strong>GW compilers. Unfortunately there is no helppage start<strong>in</strong>g the compiler with the usual help option. So you have to read the manual or download somehelp<strong>in</strong>g <strong>in</strong>formations.Figure 1.7: Setup M<strong>in</strong>GW Path AccessIf we want to compile FORTRAN sources, we can use the G77 or the GFortran compiler. The GFortrancompiler is the successor of the G77 and supports also the newer FORTRAN languages, FORTRAN 90,FORTRAN 95 and FORTRAN 2003 and parts of FORTRAN 2008.Figure 1.8 shows a simple compiler call of the GFortran compiler, which compiles the FORTRAN sourcefile and l<strong>in</strong>ks it with the used libraries. After hav<strong>in</strong>g called the compiler, we check the existents of theexecutable with a dir call. Then the executable is called and pr<strong>in</strong>ts it’s legendary hello world to thescreen. The most simple call of the compiler is shown <strong>in</strong> figure 1.8. The file hello.f is selected by the<strong>in</strong>put filter *.f. The output file is set by the option -o.Figure 1.8: Create an Executable with one Compiler Call8 More <strong>in</strong>formation about cygw<strong>in</strong> is available on the project site http://www.cygw<strong>in</strong>.com/.E. Baeck


1.7. THE G95 COMPILER Page 131.7 The G95 CompilerAlternative to the GFortran compiler you can use the G95 compiler, which provides nearly the samefeatures as the GFortran compiler.G95 determ<strong>in</strong>es how an <strong>in</strong>put file should be compiled based on its extension. Allowable file nameextensions for Fortran source files are limited to .f, .F, .for, .FOR, .f90, .F90, .f95, .F95, .f03 and .F03.The filename extension determ<strong>in</strong>es whether Fortran sources are to be treated as fixed form, or free format.Files end<strong>in</strong>g <strong>in</strong> .f, .F, .for, and .FOR are assumed to be fixed form source compatible with old f77 files.Files end<strong>in</strong>g <strong>in</strong> .f90, .F90, .f95, .F95, .f03 and .F03 are assumed to be free source form. Files end<strong>in</strong>g <strong>in</strong>uppercase letters are pre-processed with the C preprocessor by default, files end<strong>in</strong>g <strong>in</strong> lowercase lettersare not pre-processed by default. The basic options for compil<strong>in</strong>g Fortran sources with g95 are:-c Compile only, do not run the l<strong>in</strong>ker.-v Show the actual programs <strong>in</strong>voked by g95 and their arguments. Particularly useful for track<strong>in</strong>gpath problems.-o Specify the name of the output file, either an object file or the executable. An .exe extension isautomatically added on W<strong>in</strong>dows systems. If no output file is specified, the default output file isnamed a.out on unix, or a.exe on W<strong>in</strong>dows systems.<strong>Info</strong>rmations about the compiler package are available on the project site http://g95.org.1.8 The Code::Blocks IDECode::Blocks was developed as a free C++ cross platform IDE. A FORTRAN version of Code::Blocks isavailable on the project site http://darmar.vgtu.lt/.Code::Blocks is not written for a specific development package. The IDE provides a very general <strong>in</strong>terfacewhich is able to support a wide variety of compilers.Figure ?? shows the start<strong>in</strong>g page of Code::Blocks. You can create a new project or can open an alreadyexist<strong>in</strong>g project. You can also select one project from the recent list.To configure the compiler sett<strong>in</strong>gs the menu command Sett<strong>in</strong>gs/Compiler and debugger... should beexecuted. The first l<strong>in</strong>e selects the compiler for the file respectively the project. The tab compiler flagsshows all supported compiler flags. With<strong>in</strong> the tab Toolcha<strong>in</strong> executable the compiler, l<strong>in</strong>ker and makeutility executable are set.Figure 1.11 shows the hello world FORTRAN source file <strong>in</strong> an editor w<strong>in</strong>dow. The color<strong>in</strong>g supportsthe FORTRAN syntax. There are FORTRAN key-word lists for a fast completion of key words writ<strong>in</strong>gsource files. With<strong>in</strong> the left browser w<strong>in</strong>dow all files of the project are listed <strong>in</strong> tree mode. With<strong>in</strong> the rightw<strong>in</strong>dow you f<strong>in</strong>d the editor w<strong>in</strong>dow and below the editor w<strong>in</strong>dow the output section with <strong>in</strong>formationconcern<strong>in</strong>g the build tool cha<strong>in</strong> execution.To check the execution of an application, a breakpo<strong>in</strong>t is set on the first source l<strong>in</strong>e 1.12. The debugg<strong>in</strong>gsession is started with the menu command Debug/Start or with the F8 key. The execution is stopped atthe first breakpo<strong>in</strong>t, that is the second l<strong>in</strong>e of code. The yellow arrow shows the execution position of theprogram.7.8.2013


Page 14 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure 1.9: Start<strong>in</strong>g Code::BlocksThe execution of the compiled and l<strong>in</strong>ked application is started with the menu command Build/Run orwith the Ctrl-F10 key (see figure 1.13). The program is executed with<strong>in</strong> a console w<strong>in</strong>dow and stops atthe end of execution. The w<strong>in</strong>dow will be closed with any key.E. Baeck


1.8. THE CODE::BLOCKS IDE Page 15Figure 1.10: Setup the Projects Compiler Sett<strong>in</strong>gsFigure 1.11: Code::Blocks Editor with hello world Source7.8.2013


Page 16 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure 1.12: Debugg<strong>in</strong>g the hello world ApplicationFigure 1.13: Run the hello world ApplicationE. Baeck


2FORTRAN BasicsThe description of FORTRAN 77 can be taken from the WATCOM FORTRAN Language Reference[2].A detailed description of all statements is given there. The description of G95 and GFortran is availableon the <strong>Info</strong>.<strong>Server</strong> 1 with the documents G95Manual.pdf and GFortran.pdf.2.1 Structur of a FORTRAN ProgramA FORTRAN program consists of a mixture of executable and non executable statements, which mustoccur <strong>in</strong> a specific order. So the FORTRAN program is divided <strong>in</strong>to three sections.• The Declaration SectionThe first section is the declaration section with it’s non executable statements of declaration. Hereall variables and constants or parameters are declared. Variables are optional <strong>in</strong>itialized.• The Execution SectionThe second section is the execution section with it’s executable statements. This is the mostly thelargest section, because this section conta<strong>in</strong>s all the statements, which describe what’s to do. Andmostly there is a lot to do.• The Term<strong>in</strong>ation SectionThe term<strong>in</strong>ation section consists of statements, which stop the execution of the program and tell<strong>in</strong>gthe compiler, that the program is complete.All FORTRAN statements should satisfy this requirements. If statements are found <strong>in</strong> the wrong section,the compiler stops compil<strong>in</strong>g and the executable will not be build.1 See http://<strong>in</strong>fo.baustatik.uni-due.de module Lehre/CM-CLFE. Actual versions are available on the project’s site.17


Page 18 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.2 Format and CommentsComment l<strong>in</strong>es are denoted by plac<strong>in</strong>g a ”C” or ”*” <strong>in</strong> column one of the l<strong>in</strong>e. Blank l<strong>in</strong>es are treatedas comment l<strong>in</strong>es too. Comment l<strong>in</strong>es may be placed anywhere <strong>in</strong> the program source (i.e., they mayappear before a FORTRAN statement, they may be <strong>in</strong>term<strong>in</strong>gled with cont<strong>in</strong>uation l<strong>in</strong>es, or they mayappear after a statement). There is no restriction on the number of comment l<strong>in</strong>es. Comment l<strong>in</strong>es mayconta<strong>in</strong> any characters from the processor character set.Watcom FORTRAN 77 and the standardized with FORTRAN 90 allow end-of-l<strong>in</strong>e comments. If a ”!”character appears <strong>in</strong> column 1 or anywhere <strong>in</strong> the statement portion of a source l<strong>in</strong>e, the rema<strong>in</strong>der ofthat l<strong>in</strong>e is treated as a comment unless the ”!” appears <strong>in</strong>side quotation marks or <strong>in</strong> column 6, if it’s afixed format file.The FORTRAN 77 has by default the format shown <strong>in</strong> table 2.1.Columns Remarks01 - 05 Column for label numbers (1 to 99999). Column 1 is also used to set comment l<strong>in</strong>es.06 Column 6 marks a cont<strong>in</strong>uation l<strong>in</strong>e for the previous l<strong>in</strong>e. The mark character can beevery character of the FORTRAN character set but not zero or a blank. By defaultthere are up to 19 cont<strong>in</strong>uation l<strong>in</strong>es available.07 - 72 Column for statements.73 - 80 Comment Column. And are used <strong>in</strong> the days of the punch cards as card number field.Table 2.1: Fixed Fortran FormatSome source of errors related to the fixed format are discussed below.• You should check the length of the code l<strong>in</strong>e. If the code l<strong>in</strong>e runs <strong>in</strong>to the number<strong>in</strong>g field, i.e. <strong>in</strong>tothe columns 73 to 80, the code will be truncated and this can produce a very subtle error situation.• If the code is shifted <strong>in</strong>to the header section of a l<strong>in</strong>e, i.e. <strong>in</strong>to the columns 1 to 6, the code alsowill be truncated, but it’s more probable, that the compiler will detect this error.In free format FORTRAN which is <strong>in</strong>troduced by standard with the FORTRAN 90 the sources are nomore restricted by some fixed column positions. So the ”C” - comment character is no more availableand the cont<strong>in</strong>uation column as well. A comment is always start<strong>in</strong>g with the exclamation mark ”!” anda cont<strong>in</strong>uation l<strong>in</strong>e is <strong>in</strong>troduced by the cont<strong>in</strong>uation character ”&” of the previous l<strong>in</strong>e which should becont<strong>in</strong>ued.The follow<strong>in</strong>g example shows an implementation of the helloworld application which only will write it’shello to the screen <strong>in</strong> a fixed formatted cod<strong>in</strong>g. The first l<strong>in</strong>e is a comment l<strong>in</strong>e, note the ”c” character <strong>in</strong>the first column. The third l<strong>in</strong>e is a cont<strong>in</strong>uation l<strong>in</strong>e, note the used cont<strong>in</strong>uation column 6. So the ”Helloaga<strong>in</strong>!” is pr<strong>in</strong>ted directly beh<strong>in</strong>d the ”Hello World”. The last l<strong>in</strong>e closes the program code.List<strong>in</strong>g 2.1: Pr<strong>in</strong>t one Hello1 c234567 this is a comment2 write ( * , * ) ’Hello World!’3 endE. Baeck


2.3. CHARACTER SET Page 19List<strong>in</strong>g 2.2: Pr<strong>in</strong>t a second Hello1 c234567 this is a comment2 write ( * , * ) ’Hello World’,3 & ’ Hello aga<strong>in</strong>!’4 endThe next implementation of the Hello Word application uses the FORTRAN 90 free format.List<strong>in</strong>g 2.3: Pr<strong>in</strong>t two Hellos with 901 !234567 this is a comment2 write ( * , * ) ’Hello World’, & ! this is a 2nd comment3 ’ Hello Aga<strong>in</strong> to 90!’4 endYou see with<strong>in</strong> the first l<strong>in</strong>e of code the ”c” character was substituted by an exclamation mark ”!”. Allcode is shifted to the 1st column. A l<strong>in</strong>e end comment is used <strong>in</strong> the 2nd l<strong>in</strong>e us<strong>in</strong>g the exclamation mark”!”. Right before the l<strong>in</strong>e end comment the l<strong>in</strong>e cont<strong>in</strong>uation character ”&” is set. The code position <strong>in</strong>the 3rd l<strong>in</strong>e is arbitrary. The end statement aga<strong>in</strong> closes the code.2.3 Character SetThe character set of FORTRAN 77 is the follow<strong>in</strong>g. 2• upper case letter A - Z• 10 digits 0 - 9• the 12 special characters: + - * / = ( ) : , . ’ $ and the space character.The character set of FORTRAN 90/95 is the follow<strong>in</strong>g. 3• upper case letter A - Z• lower case letter a -z• 10 digits 0 - 9• Miscellaneous common symbols, such as + - * / = ( ) : , . ’ $ ” { } [ ] !• and any special letter of symbol required by the language, such as ä, ö, ü.2.4 Available Data FormatsThe types of data format available on a computer are depend<strong>in</strong>g on the hardware. General there aresome <strong>in</strong>teger formats for <strong>in</strong>teger values available. Standard is a short type with 2 bytes and a long type2 Modern FORTRAN 77 compiler support also lower case letters.3 The ASCII cod<strong>in</strong>g system which is used <strong>in</strong> comput<strong>in</strong>g stores one character <strong>in</strong> one byte. So ASCII is able to code maximal256 characters. To support languages with more then 256 characters the Unicode cod<strong>in</strong>g, a multibyte cod<strong>in</strong>g, was developed,which is also supported by the actual FORTRAN 90/95.7.8.2013


Page 20 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13with 4 bytes. With the development of the 64 bit operat<strong>in</strong>g systems also 8 byte <strong>in</strong>tegers are available.Especially this is necessary to access to large files with a size larger then 2 GB or to be able to handlememory blocks with a size above 2 GB. On W<strong>in</strong>dows32 with some provider depend<strong>in</strong>g tricks this wasalready possible, but accord<strong>in</strong>g to a standard it was not till 64 bit systems are available.For floats general two formats are available, a 4 byte real and a 8 byte real. In the case of complexcalculations as solv<strong>in</strong>g a l<strong>in</strong>ear equation system it is strongly recommended to use the 8 byte float.With<strong>in</strong> the follow<strong>in</strong>g table data types are listed with there specific properties.Type Size RestrictionINTEGER 2 Bytes Range −2 15 · · · 2 15 − 1 = 32767INTEGER 4 Bytes Range −2 31 · · · 2 31 − 1 = 2147483647 ≈ 2.14 · 10 9INTEGER 8 Bytes Range −2 63 · · · 2 63 − 1 = 9, 22 · 10 18REAL 4 Bytes Exponent range −38 · · · 38, 7 digits precisionREAL 8 Bytes Exponent range −308 · · · 308, 15 digits precisionCHARACTER 1 Byteone byte characterTable 2.2: General Data Types with their Restrictions2.4.1 Negative NumbersNegative numbers can be represented by complements of the positive number. Each digit of then positivenumber and it’s complement gives the maximum value of the digit. This would be 1 with<strong>in</strong> theb<strong>in</strong>ary system. Table 2.3shows the scheme for the construction of a negative number for 7 us<strong>in</strong>g theb-complement.Comments0000|0111 2 07 16 , the positive number has the value 71111|1000 2 FA 16 , number complement of 7, 1 -digit+ 1 2 b-complement = complement +11111|1001 2 b-complement or negative numberCheck of the b-complement to be the searched negative number0000|0111 2 positive number+ 1111|1001 2 b-complement or negative number1|0000|0000 2 The overflow<strong>in</strong>g bit will be truncated and therefor the sum vanishes.Table 2.3: Construction of a negative Number2.5 Data Types, Variables and ConstantsWith<strong>in</strong> the follow<strong>in</strong>g section we will discuss the available data types for the variables of FORTRAN 77and FORTRAN 90 and above. We will discuss how to declare and <strong>in</strong>itialize variables and constants.E. Baeck


2.5. DATA TYPES, VARIABLES AND CONSTANTS Page 212.5.1 Data Types of FORTRAN 77Table 2.4 shows the available data types of FORTRAN 77 under standard.Type Comment ExampleINTEGER Integer number 15, -100, 2500REAL Float<strong>in</strong>gpo<strong>in</strong>t number, s<strong>in</strong>gle precision 3.1415, -5.5, .7E3, 12.5E-5DOUBLE PRECISION Float<strong>in</strong>gpo<strong>in</strong>t number, double precision3.1415D0, -5.5D0, .7D3, 12.5D-5COMPLEXComplex numbers, (two REAL numbers)(3.1415, -5.5), (1.4, 7.1E4)LOGICAL Logical values .TRUE., .FALSE.Table 2.4: Fortran 77 Data TypesBecause the standard FORTRAN 77 only supports this few data types, the de facto standard of the FOR-TRAN 77 implementation supports some data types more, which are def<strong>in</strong>ed by the number of used bytestoo.INTEGER*4, REAL*4, LOGICAL*4, (default on 32 bit platforms)INTEGER*1, LOGICAL*1INTEGER*2, LOGICAL*2REAL*8 (on 32 bit platforms the same as DOUBLE PRECISION)COMPLEX*16 (complex numbers with two DOUBLE-PRECISION numbers)4 bytes1 byte2 bytes8 bytes16 bytesBecause there is no str<strong>in</strong>g handl<strong>in</strong>g <strong>in</strong> the standardized FORTRAN 77 de facto there is a standard oftreat<strong>in</strong>g str<strong>in</strong>gs <strong>in</strong> FORTRAN 77.• A character like ’A’ can be stored <strong>in</strong> the data type CHARACTER or CHARACTER*1.• A str<strong>in</strong>g of n characters like ’The End!’ can be stored <strong>in</strong> the data type CHARACTER*n.2.5.2 Data Types s<strong>in</strong>ce FORTRAN 90Table 2.5 shows the available <strong>in</strong>tr<strong>in</strong>sic build<strong>in</strong> data types of FORTRAN 90 under standard.Type Comment ExampleINTEGER Integer number 15, -100, 2500REAL Float<strong>in</strong>gpo<strong>in</strong>t number, s<strong>in</strong>gle precision 3.1415, -5.5, .7E3, 12.5E-5COMPLEX Complex numbers, (two REAL numbers) (3.1415, -5.5), (1.4, 7.1E4)LOGICAL Logical values .TRUE., .FALSE.CHARACTER Str<strong>in</strong>g variable with given length’This is a str<strong>in</strong>g! Hey!’Table 2.5: Fortran 90 Data Types7.8.2013


Page 22 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Because there are de facto so many special data types <strong>in</strong> FORTRAN 90 a new concept was <strong>in</strong>troducedto setup the desired byte length of a data type with the so called KIND number. The KIND number isdepended of the implementation of the FORTRAN 90, that means that the byte length is not generallyknown, if the KIND number is given. The KIND number of a given value can be evaluated by the functionKIND.The follow<strong>in</strong>g FORTRAN 90 code evaluates the KIND number of 0.0 and 0.0d0, i.e. of s<strong>in</strong>gle and doubleprecision for the gfortran compiler on 32 bit W<strong>in</strong>dows XP. 4List<strong>in</strong>g 2.4: Evaluat<strong>in</strong>g the K<strong>in</strong>d Number 901 ! Program to evaluate the k<strong>in</strong>d number of2 ! - s<strong>in</strong>gle precision (REAL)3 ! - double precision (DOUBLE PRECISION)4 program k<strong>in</strong>ds5 write( * ,’(" K<strong>in</strong>d of s<strong>in</strong>gle precision:",i2)’) k<strong>in</strong>d(0.0) ! it’s s<strong>in</strong>gle6 write( * ,’(" K<strong>in</strong>d of double precision:",i2)’) k<strong>in</strong>d(0.0d0) ! it’s double7 end programFigure 2.1 shows the compile and execution step of the K<strong>in</strong>d application. And you can see from theoutput, that s<strong>in</strong>gle precision gives a KIND number of 4, double precision a KIND number of 8 like real*4aund real*8 <strong>in</strong> the case FORTRAN 77 standard extension (see above).Figure 2.1: Evaluat<strong>in</strong>g the K<strong>in</strong>d Numbers2.5.3 Data RangesIf you select a data type for an implementation, then you should know the available data range of thatdata type. The data range can be depended of the <strong>in</strong>stalled operat<strong>in</strong>g system and from the processorhimself. So an <strong>in</strong>teger of the W<strong>in</strong>dows3 has half the range as the <strong>in</strong>teger from W<strong>in</strong>dowsXP, if the rangeis not explicit set us<strong>in</strong>g the * version of the data type. If a not properly data type is selected, then thecode will be <strong>in</strong>efficient if the data range is larger than needed. If the data range is smaller then needed,the code will not run properly because the data will go out of range, which will result an overflow withall it’s unpredictable consequences 5 .The follow<strong>in</strong>g table shows the ranges of the FORTRAN 77 data types.4 You see, that <strong>in</strong> FORTRAN 90 a program starts with the key word program and ends with end program.5 If you will implement a complex calculation algorithm with a lot of operations like the triangulation of a matrix, then youshould use the double precision data types, to avoid a losses of <strong>in</strong>formation.)E. Baeck


2.5. DATA TYPES, VARIABLES AND CONSTANTS Page 23Daten TypeBytes Data RangeINTEGER*1 1 −128 · · · + 127INTEGER*2 2 −32768 bis +32767 = 2 15 − 1INTEGER*4 4 −2 31 bis +2 31 − 1 ≈ 2 · 10 9REAL*4 4 ±10 ±38 , precision of 7 digits.REAL*8 8 ±10 ±308 , precision of 16 digits.2.5.4 Declaration of Variables and Constants <strong>in</strong> FORTRAN 77With an explicit declaration the data type of variables and parameter (constants) is set. The declarationsshould be made <strong>in</strong> the header section of a program or a subprogram, which is the section before the firstexecutable statement is made (like an assignment or a write statement).The declaration is given by: Data Type [List of Variables]The list of variables contents one or more variable names, which are separated by commas.The follow<strong>in</strong>g example shows the declaration of the variables V1,V2 and V3, which are declared asREAL*4. The variables I1,I2 and I3 are declared as INTEGER*2.List<strong>in</strong>g 2.5: Declaration <strong>in</strong> 66/771 c2345672 REAL*4 V1,V2,V33 INTEGER*2 I1,I2,I3Constants are called PARAMETER <strong>in</strong> FORTRAN 77. A constant is declared by an additional PARAM-ETER statement. The PARAMETER def<strong>in</strong>es the value of the constant. This value is set by compilationand can not changed at run time (therefor it’s called a constant).The parameter is set by: PARAMETER (name = value)The follow<strong>in</strong>g example declares three real variables and three <strong>in</strong>teger parameters.List<strong>in</strong>g 2.6: Declaration and Parameters <strong>in</strong> 66/771 c2345672 REAL*4 V1,V2,V33 INTEGER*2 I1,I2,I34 PARAMETER (I1 = 4)5 PARAMETER (I2 = 8)6 PARAMETER (I3 = I1+I2)With<strong>in</strong> the declaration section of a program variable can be <strong>in</strong>itialized with the statement DATA, whichfollows the declaration of the variables to be <strong>in</strong>itialized.List<strong>in</strong>g 2.7: Declaration and Initialization <strong>in</strong> 66/771 c2345672 REAL*4 V1,V2,V33 INTEGER*2 I1,I2,I34 DATA I1 /4/, I2 /8/, I3 /12/7.8.2013


Page 24 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.5.5 Declaration of Variables and Constants <strong>in</strong> FORTRAN 90The declaration of variables <strong>in</strong> FORTRAN 90 is slightly different from the FORTRAN 77 format and isgiven by the follow<strong>in</strong>g statement.Data Type :: List of VariablesIn the follow<strong>in</strong>g example the three <strong>in</strong>teger variables month, day and year are declared. In the secondl<strong>in</strong>e the real variable seconds is declared. The character variables which should store some str<strong>in</strong>gsshould be declared with a properly length. The first declaration shows the declaration with an explicitlength parameter, the second declaration uses only the value of the length.List<strong>in</strong>g 2.8: Declaration <strong>in</strong> 90++1 INTEGER :: day, month, year2 REAL :: seconds3 CHARACTER(len = 10) :: prename4 CHARACTER(20) :: famnameIn the follow<strong>in</strong>g example you can see how to <strong>in</strong>itialize the just declared variables. This is like declarationand <strong>in</strong>itialization <strong>in</strong> the language C simply with<strong>in</strong> one step. So the obsolete statement DATA is no longerneeded and can be canceled from modern FOTRAN 90 sources (see also section 2.5.4).List<strong>in</strong>g 2.9: Declaration and Initialization <strong>in</strong> 90++1 INTEGER :: day = 16, month = 10 , year = 20102 REAL :: seconds = 10.53 CHARACTER(len = 10) :: prename = ’Ernst’4 CHARACTER(20) :: famname = ’Baeck’The follow<strong>in</strong>g example shows, how to declare parameters (constants). You see the code is very simularcompared with the previous code. Only the attribut PARAMETER was added. With<strong>in</strong> the first code thecontent of the variables can be changed by an assignment. With<strong>in</strong> the second code, we have declaredparameters and the content of this parameters can not be changed, because a parameter is fixed. So yousee, that the FORTRAN 77 statement PARAMETER, now obsolete, is also no longer necessary and canbe deleted from modern FORTRAN 90 code (see also section 2.5.4).List<strong>in</strong>g 2.10: Declaration and Parameters <strong>in</strong> 90++1 INTEGER, PARAMETER :: day = 16, month = 10 , year = 20102 REAL, PARAMETER :: seconds = 10.53 CHARACTER(len = 10), PARAMETER :: prename = ’Ernst’4 CHARACTER(20), PARAMETER :: famname = ’Baeck’2.6 OperatorsFortran offers a set of operators, which are offered from the most computer languages. Fortran usesthe same precedence as we know form the mathematics. The power operation has the strongest b<strong>in</strong>d<strong>in</strong>gfollowed by the po<strong>in</strong>t operators (products and divisions) followed by the l<strong>in</strong>e operators (plus and m<strong>in</strong>us).Unary operators will always be applied first. To change the standard precedence of the operators we uselike <strong>in</strong> mathematics parenthesis to dictate the way a formula should be evaluated.E. Baeck


2.6. OPERATORS Page 252.6.1 Unary OperatorsUnary operators are work<strong>in</strong>g only on one value, therefor unary. In Fortran there are the follow<strong>in</strong>g unaryoperators available.Operator CommentExample+ plus operator a = 2 >>> x = +a >>> +2- m<strong>in</strong>us operator a = 2 >>> x = -a >>> -2.not. logical <strong>in</strong>verse a = .false. >>> x = .not.a >>> .true.2.6.2 Arithmetic OperatorsFortran offers the follow<strong>in</strong>g arithmetic operators. You should be careful with the usage of data typesespecially with<strong>in</strong> divisions. If you use <strong>in</strong>tegers, the result generally will be truncated.Operator CommentExample+ sum operator x = 2+3 >>> 5- subtraction operator x = 4-2 >>> 2* product operator x = 2*4 >>> 8/ division operator x = 9/2 >>> 4x = 9./2. >>> 4.5** power operator x = a**2// concatenate of str<strong>in</strong>gs x = "hello"//"world" >>> "hello world"2.6.3 Comparison OperatorsBoolean operators are used to branch and to make decisions. The compar<strong>in</strong>g operators of Fortran 90 arenow nearly identical to the C compar<strong>in</strong>g operators.Operator CommentExample.lt. less than x = 23 .lt. 13 >>> .false..le. less equal x = 23 .le. 23 >>> .true..gt. greater x = 23 .gt. 13 >>> .true..ge. left shift of bits x = 23 .ge. 23 >>> .true..eq. equal x = 23 .eq. 23 >>> .true..ne. not equal x = 23 .ne. 13 >>> .false.With<strong>in</strong> Fortran 90 there also C like compar<strong>in</strong>g operators available.7.8.2013


Page 26 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Operator CommentExample< less than x = 23 < 13 >>> .false.> .true.> greater x = 23 > 13 >>> .true.>= left shift of bits x = 23 >= 23 >>> .true.== equal x = 23 == 23 >>> .true./= non equal x = 23 /= 23 >>> .false.The result of a boolean expression like above are the boolean values .false. or .true.. To comb<strong>in</strong>ecompar<strong>in</strong>g expressions the follow<strong>in</strong>g logical operators can be used. 67Operator Comment Example.and. logical and x = 1 .lt. 2 .and. 2 .lt. 3 >>> .true..or. logical or x = 1 .lt. 2 .or. 2 .gr. 3 >>> .true..equ. logical or x = .true. >>> y = .false. >>> x .eqv. y >>> .false..nequ. logical or x = .true. >>> y = .false. >>> x .neqv. y >>> .true..not. logical not x = .not. (1 .lt. 2) >>> .false.The truth table for the AND operator ∧ is given as follows..true. ∧ .true. = .true. (2.1).true. ∧ .false. = .false..false. ∧ .true. = .false..false. ∧ .false. = .false.The truth table for the OR operator ∨ is given as follows..true. ∨ .true. = .true. (2.2).true. ∨ .false. = .true..false. ∨ .true. = .true..false. ∨ .false. = .false.2.7 File IO, Screen and KeyboardTo communicate with the program the two statements read and write are necessary. In the most simplecase we read the <strong>in</strong>put data from the keyboard and write the output data <strong>in</strong>to a console w<strong>in</strong>dow. A simpleoutput gives us the example helloworld, see section 2.2.6 To make expressions clear parenthesis should be used. A term with<strong>in</strong> a parenthesis is evaluated first and it’s result then isused <strong>in</strong> further evaluations outside the parenthesis. With parenthesis the order of the evaluation can be set.7 The logical operator .NEQV. implements the exclusive OR.E. Baeck


2.7. FILE IO, SCREEN AND KEYBOARD Page 272.7.1 Open a FileThe open statement assigns a file name to a channel number. Every read or write access to this file usesthis channel number. An open statement also has to set up the access type with the status parameter.The open<strong>in</strong>g of a file should be checked by the iostat parameter.Some status values of the open statement are discussed <strong>in</strong> the table below. In Fortran77 only ’new’and ’old’ are available.status’old’’new’CommentThe file must existA new file is created. No file with this name must exist.’replace’ A new file is created. No matter whether there is an old file ornot.’scratch’ A temporary file is created, a file name is not needed. if the file isclosed, the file is automatically removed’unknown’ The same as ’replace’. It’s a pre Fortran90 statement andshould be replaced by ’replace’The access type can be specified with the ’action’ parameter. The available values are discussed <strong>in</strong>the table below. This is only available <strong>in</strong> Fortran90.action’read’’write’CommentFhe file is opened only for read access.Fhe file is opened only for write access.’readwrite’ This ’action’ is set if the parameter is not given. The file isopened for read<strong>in</strong>g and writ<strong>in</strong>g.2.7.2 Writ<strong>in</strong>g Texts, write StatementThe write statement has two parameters and a data list.1 WRITE (,) Parameter 1 sets up the output channel. If we use the value *, the output is written <strong>in</strong>to the console. Ifwe use an <strong>in</strong>teger number, we have to open a channel before for writ<strong>in</strong>g and assign this channel with thedesired channel number. The follow<strong>in</strong>g example shows the usage of the console w<strong>in</strong>dow and the output<strong>in</strong>to a used channel.1 write ( *,*) ’Hallo my Channel’ ! output <strong>in</strong>to the console2 write (10,*) ’Hallo Channel 10’ ! output <strong>in</strong>to channel 10Parameter 2 sets up the output format. If we use the value *, a standard format is used. Str<strong>in</strong>gs arewritten <strong>in</strong> total length and values, <strong>in</strong>teger or floats, are written with full precision.The follow<strong>in</strong>g format types can be applied.7.8.2013


Page 28 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.7.3 Formatt<strong>in</strong>g, FORMAT StatementIf data should be formatted, we can use the format statement or we can use the parameter of the formatstatement as str<strong>in</strong>g as parameter 2 of the write statement. The general form of an output format is[m]Tw[.n].1. Format Type T• I, <strong>in</strong>teger format.• F, float format with fixed decimal po<strong>in</strong>t.• E, float format with exponential representation.• A, text format, the with of the format is optional.• X, output of spaces• /, a new l<strong>in</strong>e, l<strong>in</strong>ebreak2. repeat factor m3. width of the output field w4. number of significant digits n with<strong>in</strong> float formatt<strong>in</strong>g.If n is used <strong>in</strong> <strong>in</strong>teger formatt<strong>in</strong>gs, the lead<strong>in</strong>g blanks are filled with zeros.Formats can also be iterated by iteration factors. If more complex formats should be iterated, the formatblock must be bracketed by round parentheses. With<strong>in</strong> the follow<strong>in</strong>g example the output of 3 variablevalues a, b and c should be written. We use one format with an iteration of 3. The format starts with2 blanks (2x). Then a text will be written, (a format) and at the end the value of the variable shouldbe written us<strong>in</strong>g a fixed float format (f). The output should have a width of 10 with 2 digits after thedecimal po<strong>in</strong>t.1 c W| 1 2 3 4 5 6 72 c234567890123456789012345678901234567890123456789012345678901234567890123 write(*,8000) ’a=’,a,’b=’,b,’c=’,c4 8000 format(3(2x,a,f10.2))2.7.4 Read from Keyboard or FileThe read statement is similar to the write statement. We simply exchange source and dest<strong>in</strong>ation.The first parameter of the read statement passes the io channel. The second parameter passes the <strong>in</strong>putformat. If a * is given, the format is free. That is, the <strong>in</strong>put <strong>in</strong>formation units are separated by blanks(white spaces). Optionally a read io error can be handled by the iostat parameter.1 READ (, [,]) E. Baeck


2.8. LOOPS Page 292.7.5 Close a FileIf an open file is no longer needed, the file should be closed. Optionally with the status parameter thefile can be deleted (’delete’) or saved. If the status parameter is not given, a standard file is kept(’keep’).1 CLOSE (, [])2.8 LoopsWith<strong>in</strong> this section we discuss the explicit loop statement. Until the FORTRAN 90 there are no statementsto cancel the loop or to cancel a cycle to start the next one immediately. With<strong>in</strong> the FORTRAN versionsup to 77 this statements have to be implemented by explicit jumps us<strong>in</strong>g goto statements.2.8.1 Explicit Loops with Counter <strong>in</strong> 66, 77 and 90+A loop that executes a block of statements a specified number of times is called an iterative DO loop orcount<strong>in</strong>g loop. A count<strong>in</strong>g loop construct has the follow<strong>in</strong>g form <strong>in</strong> FORTRAN 66, where <strong>in</strong>dex is thecount<strong>in</strong>g variable, which starts with the value istart and iterates up to the value iend. After each cyclethe count<strong>in</strong>g variable is <strong>in</strong>cremented by <strong>in</strong>c. If <strong>in</strong>c is not given, <strong>in</strong>c is set to 1. In FORTRAN 66 the DOstatement needs an end<strong>in</strong>g label number (<strong>in</strong> this example 100). The loop executes all l<strong>in</strong>es of code untilthe l<strong>in</strong>e with the given label number.1 c DO loop <strong>in</strong> FORTRAN662 c2345673 do 100 <strong>in</strong>dex = istart, iend [, <strong>in</strong>c]4 5 100 cont<strong>in</strong>ueIn FORTRAN 77 the labeled DO is substituted by a DO ... END DO construct. S<strong>in</strong>gle loop cycles as wellas the total loop can be broken by a goto statement jump<strong>in</strong>g to an appropriate label.1 c DO loop <strong>in</strong> FORTRAN902 c2345673 do <strong>in</strong>dex = istart, iend [, <strong>in</strong>c]4 5 end doA loop cycle can be broken by the statement cycle. The cycle statement breaks the actual cycleand starts the next one, if a new cycle should be executed. The total loop can be broken by an exitstatement.If we want apply the FORTRAN 90 we use the free format. 81 ! DO loop <strong>in</strong> FORTRAN902 do <strong>in</strong>dex = istart, iend [, <strong>in</strong>c]3 4 end do8 Please note, that there are a lot of non standardized loop constructions, which are added to some Fortran 77 implementationslike Watcom77. In section ?? you will f<strong>in</strong>d a Basic like loop structure mit LOOP...UNTIL (BOOLEAN EXPRESSION).This loop statement is not supported by standard and so it should be substituted by the new Fortran 90 version.7.8.2013


Page 30 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.8.2 Simple Nested Loop ExampleWith<strong>in</strong> the follow<strong>in</strong>g example all we have a loop from 1 to 10 and an nested loop form 1 to 5. Thenumbers of the counter variables should be pr<strong>in</strong>ted and their product to. The implementation ist given <strong>in</strong>FORTRAN 66, FORTRAN 77 and FORTRAN 90.The FORTRAN 66 is given as follows. The outer loop is labeled by 100 and the <strong>in</strong>ner loop is labeled by50. Note that each loop needs his own unique counter variable and nested loops must be nested totally,i.e. they must not overlap.List<strong>in</strong>g 2.11: A nested 66-Loop Example1 c2345672 do 100 i=1,103 do 50 j=1,54 write( * , * ) ’i=’,i,’ j=’,j,’ i * j=’,i * j5 50 cont<strong>in</strong>ue6 100 cont<strong>in</strong>ue7 endThe FORTRAN 77 version differs from the FORTRAN 66 version only by remov<strong>in</strong>g the label and clos<strong>in</strong>gthe loop with an end do statement.List<strong>in</strong>g 2.12: A nested 77-Loop Example1 c2345672 do 100 i=1,103 do 50 j=1,54 write( * , * ) ’i=’,i,’ j=’,j,’ i * j=’,i * j5 end do6 end do7 endUs<strong>in</strong>g an <strong>in</strong>dent of code blocks <strong>in</strong> loops can be problematic because <strong>in</strong> FORTRAN 77 we only have thecolumns from 7 to 72. A much more nicer code can be received, if we use the FORTRAN 90 versionwith it’s free format<strong>in</strong>g. Now FORTRAN has the look of a realy modern language. We start with the 1stcolumn and we have enough space for <strong>in</strong>dent<strong>in</strong>g. The problem of truncat<strong>in</strong>g the code with the commentregion is no longer exist<strong>in</strong>g.List<strong>in</strong>g 2.13: A nested 90-Loop Example1 program loop902 do i=1,103 do j=1,54 write( * , * ) ’i=’,i,’ j=’,j,’ i * j=’,i * j5 end do6 end do7 end loop90E. Baeck


2.8. LOOPS Page 312.8.3 Quit a Cycle or a LoopIn FORTRAN 66 everyth<strong>in</strong>g is done us<strong>in</strong>g an goto statement, so <strong>in</strong> this dialect we use goto too to quita cycle or a the entire loop.List<strong>in</strong>g 2.14: Break<strong>in</strong>g a 66-Loop1 c234567................................................................2 do 100 i = 1,103 write(*,*)"Beg<strong>in</strong> of a cycle!"45 c for i=3 the cycle should not be executed6 if (i.eq.3) goto 10078 c break the entire loop for all i > 59 if (i.gt.5) goto 1101011 write(*,*)"i=",i12 100 cont<strong>in</strong>ue13 110 write(*,*)"End of the loop!"14 endWith FORTRAN 90 two very helpful statements came <strong>in</strong>to picture to avoid explicit jumps us<strong>in</strong>g goto.• cycle cancels the current cycle and starts the next• exit cancels the entire loopList<strong>in</strong>g 2.15: Break<strong>in</strong>g an explicit 90-Loop1 program loopescape2 do i = 1,103 write(*,*)"Beg<strong>in</strong> of a cycle!"45 ! for i=3 the cycle should not be executed6 if (i.eq.3) cycle78 ! break the entire loop for all i > 59 if (i.gt.5) exit1011 write(*,*)"i=",i12 end do1314 write(*,*)"End of the loop!"15 end program loopescape7.8.2013


Page 32 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.8.4 Implicit, General Loop without a Control Structure <strong>in</strong> 90+In Fortran 90 the do ... end do statement can be used without any control elements too, so thebreak condition of the look has to be implemented manually by the usage of an if statement (see section2.9 too). If we compare the list<strong>in</strong>gs 2.15 with 2.16, we see, that <strong>in</strong>crement<strong>in</strong>g the loop counter has to bedone manually as well as it’s <strong>in</strong>itialization. Us<strong>in</strong>g an implicit (general) loop we have to be careful withthe break condition, so that we avoid hang<strong>in</strong>g <strong>in</strong> an endless loop.List<strong>in</strong>g 2.16: Break<strong>in</strong>g a general 90-Loop1 program GeneralLoop2 i = 03 do4 i = i+15 write(*,*)"Beg<strong>in</strong> of a cycle!"67 ! for i=3 the cycle should not be executed8 if (i.eq.3) cycle910 ! break the entire loop for all i > 511 if (i.gt.5) exit1213 write(*,*)"i=",i1415 end do1617 write(*,*)"End of the loop!"18 end program GeneralLoopE. Baeck


2.8. LOOPS Page 332.8.5 Factorial <strong>in</strong> FORTRAN 90++The factorial of n is def<strong>in</strong>ed iteratively byn∏n! = i (2.3)i=1so we can translate the product easily <strong>in</strong>to a loop. A product symbol ∏ or a sum ∑ will be representedby a loop. The counter variable is given by the <strong>in</strong>dex range of the product or sum symbol. Because thefactorial uses a result variable, the product, we have to <strong>in</strong>troduce a second variable. The product resultwill be assigned to this variable.List<strong>in</strong>g 2.17: Implementation of the Factorial1 ! calculat<strong>in</strong>g the factorial2 !3 ! analys<strong>in</strong>g effects of the data type size4 ! us<strong>in</strong>g the factorial56 program factorial907 ! <strong>in</strong>teger(2) :: f ! result value <strong>in</strong>teger 2 bytes8 ! <strong>in</strong>teger(4) :: f ! result value <strong>in</strong>teger 4 bytes9 ! real(4) :: f ! result value real 4 bytes1011 real(8) :: f ! result value real 8 bytes12 <strong>in</strong>teger(2) :: i ! loop <strong>in</strong>dex variable13 <strong>in</strong>teger(2) :: n ! <strong>in</strong>put value1415 n = 20016 write(*,*) ’n = ’,n1718 f = 119 do i = 1,n2021 !new old22 f = f * i23 write(*,*) i,’! = ’,f24 end do25 end programWith<strong>in</strong> this example you can check the range of the available data types. If p is set to <strong>in</strong>teger 4 bytesare used to store the factorial. The larges <strong>in</strong>teger with<strong>in</strong> 4 bytes can be calculated as follows. 9max = 2 31 − 1 = 2147483647 ≈ 2, 147 · 10 9 (2.4)Figure 2.2 shows the problem of an overflow, if the numbers to store exceeds the limit of the data type.The factorial von 12 looks like plausible. But the next must be wrong, because 4 · 13 ≠ 19. If wecheck the next factorials, we will see, that the numbers not really exceed 2 · 10 9 . Thats the 2GB Problem.Furthermore we see, that some numbers become negative. This obvious is also wrong and a consequenceof the overflow situation.9 This is also known as 2GB problem. This problem occur for example, if a file exceeds the size of 2GB, because a 4 byte<strong>in</strong>teger is used to address the file’s bytes read<strong>in</strong>g or writ<strong>in</strong>g them. A similar problem occur, if you want to have more then 256columns <strong>in</strong> MS-EXCEL2003, that’s a one byte limit, or if you need more then 65536 rows <strong>in</strong> MS-EXCEL2003, that’s a 2 bytelimit.7.8.2013


Page 34 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure 2.2: Factorial us<strong>in</strong>g INTEGER with 4 BytesFor larger numbers the choice of a real data type is recommended. With<strong>in</strong> a real data type only theexponent can overflow. The mantissa can not overflow, because it’s <strong>in</strong>dependent of the number’s size. Ifwe use the largest available data type double precision 10 , we will get the situation of figure 2.3.We see, that with the 8 byte real the factorial reaches 170!. The next result is <strong>in</strong>dicated as Inf<strong>in</strong>ity. Thishappens, if the memory for the exponent overflows. A 4 byte real has an exponent range of −38 · · · + 38,a 8 byte real has an exponent range of −308 · · · + 308. We see, that the largest occurr<strong>in</strong>g exponent is+306.2.9 Branch<strong>in</strong>gBranch<strong>in</strong>g and decisions can be implemented <strong>in</strong> Fortran like <strong>in</strong> the most languages with an if -statement.The application of if constructs will be discussed us<strong>in</strong>g the implementation of the general form of aquadratic equation. With<strong>in</strong> a first approach the implementation <strong>in</strong> a Fortran66 like program is shown.2.9.1 if Statement, Fortran 66 likeWith<strong>in</strong> the first standardized Fortran version, which will be compiled from modern Fortran compilerstoo, the if statement is very rough. It’s like a branch <strong>in</strong> assembler language, that is, the if statement onlyis able to process one statement. Note the two statements <strong>in</strong> the macro assembler code of section 1.2.1resumed below. With<strong>in</strong> a first step, a registers data is compared. In a second step a conditional jump isperformed.1 ...2 cmp edx, 2 < compar<strong>in</strong>g the content of the edx with 23 ja @f < jump, if equal4 ...10 The data type double precision with FORTRAN 90 is obsolete, see also section 2.5.2, but can be used, if you want.E. Baeck


2.9. BRANCHING Page 35Figure 2.3: Factorial us<strong>in</strong>g Real with 8 BytesList<strong>in</strong>g 2.18: Syntax of the if Statement1 IF () Because of the similar structure of assembler branches and branches <strong>in</strong> Fortran 66 the developed Fortrancode will be very similar to the assembler code compar<strong>in</strong>g their case structures.An example to implement an implicit loop with an if statement and a backward jump to calculate therelative precision is given <strong>in</strong> section 3.3.2.9.2 Implementation of a Quadratic Equation SolverThe solver of a generall quadratic equation is a vell known problem, we know from our school days. Theimplementation whowever requires the solution of a set of subproblems, which <strong>in</strong>deed is a very goodexample to show branch<strong>in</strong>g.2.9.2.1 Some TheoryThe follow<strong>in</strong>g example implements the solver for a general quadratic equation.a · x 2 + b · x + c = 0 (2.5)We have the follow<strong>in</strong>g cases.• a = 0 ∧ b = 0 ∧ c = 0Inf<strong>in</strong>ite solutions. x can be set arbitrary.• a = 0 ∧ b = 0 ∧ c ≠ 0No solution possible.7.8.2013


Page 36 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13• a = 0 ∧ b ≠ 0L<strong>in</strong>ear case, x = −c/b.• a ≠ 0Quadratic case,x 1 = 12a (−b + √ b 2 − 4ac).x 2 = 12a (−b − √ b 2 − 4ac).2.9.2.2 A Flow-Chart of the QuadSolverThe follow<strong>in</strong>g flow chart shows all the case, which we have to handle. The algorithm is given for a realarithmetic, i.e. no complex data types are used. The relevant source code will be developed with<strong>in</strong> thenext section.Startyes yes yesa = 0 b = 0 c = 0<strong>in</strong>f<strong>in</strong>itsolutionsStopnononod = b 2 − 4 · a · cx = − c bStopno solutionStopd < 0yesx 1,2 = −b±i√ −d2·aStopnox 1,2 = −b±√ d2·aStop2.9.2.3 Quadratic Equation, Solver Implementation Fortran 66 likeThe first implementation <strong>in</strong> strict Forteran 66 shows the subsequent solution of the above discussedcases. Because the if statement can only process one statement, the <strong>in</strong>verse case should be checked tojump over the succeed<strong>in</strong>g code. After the code block a further jump should be performed to the laststatement of the program.List<strong>in</strong>g 2.19: Implementation of a 66-Quad-Solver1 c quadratic equation2 c a*x**2 + b*x + c =3 c4 c a,b,c are arbitray <strong>in</strong>put parameters5 c6 c explicit declaration should be done7 c8 c2345679 implicit none10 cE. Baeck


2.9. BRANCHING Page 3711 c <strong>in</strong>put parameters12 double precision a,b,c1314 c work<strong>in</strong>g variables15 double precision d,p1617 c output float values18 double precision x1,x21920 c output complex values21 double precision x1r,x2r,x1i,x2i2223 c Initialization24 p = 1.d-1525 a = 1.d026 b = 0.d027 c = 4.d028 c29 c <strong>in</strong>put parameters from the keyboard30 write(*,*) ’<strong>in</strong>put of a:’31 read(*,*) a32 write(*,*) ’<strong>in</strong>put of b:’33 read(*,*) b34 write(*,*) ’<strong>in</strong>put of c’35 read(*,*) c36 c37 c list <strong>in</strong>put parameters for check<strong>in</strong>g38 write(*,*) ’ Input parameters:’39 write(*,*) ’ a = ’,a40 write(*,*) ’ b = ’,b41 write(*,*) ’ c = ’,c4243 c l<strong>in</strong>ear, constant branch44 if (dabs(a) .gt. p) goto 5004546 c contant branch47 if (dabs(b) .gt. p) goto 4004849 if (dabs(c) .gt. p)50 1write(*,*) ’No solution found, constant case.’5152 if (dabs(c) .le. p)53 1write(*,*) ’Inf<strong>in</strong>it solutions found, constant case.’5455 goto 6005657 c l<strong>in</strong>ear branch58 400 cont<strong>in</strong>ue59 x1 = -c/b60 write (*,*) ’L<strong>in</strong>ear case: x = ’, x161 goto 6006263 c quadratic branch64 500 cont<strong>in</strong>ue65 c calculat<strong>in</strong>g the discrim<strong>in</strong>ante66 d = b**2 -4.d0*a*c7.8.2013


Page 38 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 136768 c reel branch69 if (d .lt. 0.) goto 5507071 d = dsqrt(d)72 x1 = (-b +d)/(2.e0*a)73 x2 = (-b -d)/(2.e0*a)7475 write(*,*) ’quadratic case, reel values’76 write(*,*) ’ x1 = ’,x177 write(*,*) ’ x2 = ’,x27879 goto 6008081 c complex branch82 550 cont<strong>in</strong>ue8384 d = dsqrt(-d)85 x1r = -b/(2.e0*a)86 x2r = x1r87 x1i = d/(2.e0*a)88 x2i = -d/(2.e0*a)8990 write(*,*) ’quadratic case, complex values’91 write(*,*) ’ x1 = ’,x1r,’ +i ’,x1i92 write(*,*) ’ x2 = ’,x2r,’ +i ’,x2i9394 600 cont<strong>in</strong>ue95 end2.9.2.4 Quadratic Equation, Solver Implementation Fortran 90 likeThe follow<strong>in</strong>g code implements the solution of a quadratic equation (see equation 2.5) <strong>in</strong> a Fortran 90version. Note, that we are able to implement the case tree without any goto jumps, which were essential<strong>in</strong> an 66 approach.List<strong>in</strong>g 2.20: Implementation of a 90-Quad-Solver1 ! Solver for a quadratic equation2 ! Implementation <strong>in</strong> Fortran903 program quadequation45 implicit none ! only explicit declarations67 real(8)::a, b, c ! parameters of the equation8 real(8)::d ! discrim<strong>in</strong>ant9 real(8)::p ! precision10 real(8)::x1,x2 ! for the real solutions11 real(8)::x1r,x1i,x2r,x2i! for the complex solutions1213 ! setup the parameters for the quadratic equation14 a = 1.15 b = 0.16 c =-4.E. Baeck


2.9. BRANCHING Page 3917 p = 1.d-151819 ! pr<strong>in</strong>t parameters values to the screen20 write(*,’(3(a,F10.3))’) ’a=’,a,’ b=’,b,’ c=’,c2122 ! case a=0: it’s not a quadratic equation!23 if (dabs(a) < p) then2425 ! subcase b=0: => <strong>in</strong>f<strong>in</strong>it solutions or no solution26 if (dabs(b) < p) then2728 ! subcase c=0: Trival case => <strong>in</strong>f<strong>in</strong>it solutions29 ! it’s <strong>in</strong>dependent of x30 if (dabs(c) < p) then31 write(*,*) ’Trivial solution, <strong>in</strong>f<strong>in</strong>it solutions for x.’3233 ! subcase c!=0: Trivial solution => no solution34 ! it’s <strong>in</strong>dependent of x35 else36 write(*,*) ’No solution found.’3738 endif3940 ! subcase b!=0 => l<strong>in</strong>ear case -> one solution41 else42 write(*,’(a,f12.5)’) ’L<strong>in</strong>ear case: x=’,-c/b4344 endif4546 ! a!=0 => quadratic problem -> two solutions47 ! if we solve the problem with reals, we have to handle48 ! the real and the complex subcase.49 else5051 ! calculate the discrim<strong>in</strong>ant to make the case check52 d = b**2 -4.*a*c5354 ! positive discrim<strong>in</strong>ant -> 2 real roots55 if (d >= 0.) then56 x1 = 1./(2.*a)*(-b +sqrt(d))57 x2 = 1./(2.*a)*(-b -sqrt(d))58 write(*,’(2(a,f12.5))’) ’Quadratic real case, x1=’,x1,’ x2=’,x25960 ! negative discrim<strong>in</strong>ant -> 2 complex roots61 else62 x1r = -b/(2.*a)63 x2r = x1r64 x1i = 1./(2.*a)*sqrt(-d)65 x2i = -x1i66 write(*,’(4(a,f12.5))’) ’Quadratic complex case, x1r=’,x1r, &67 ’ x1i=’,x1i, ’ x2r=’,x2r,’ x2i=’,x2i68 endif6970 endif71 end program7.8.2013


Page 40 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.10 Subrout<strong>in</strong>es and FunctionsA very important feature of a programm<strong>in</strong>g language is the possibility to encapsulate code <strong>in</strong>to reusablepackages. Such a package is called <strong>in</strong> Fortran Subrout<strong>in</strong>e or Function. The only difference betweena function and a subrout<strong>in</strong>e is the return value of the function. So a function can be called with<strong>in</strong>an expression like s<strong>in</strong>(ϕ) or cos(ϕ). A function as well as a subrout<strong>in</strong>e <strong>in</strong> general receives a list ofparameters, which are called formal parameters. A parameter can be used to pass <strong>in</strong>formation from thecall<strong>in</strong>g program <strong>in</strong>to the function or the subrout<strong>in</strong>e. Then the parameter is called <strong>in</strong>put parameter. Aparameter can be used as well to pass <strong>in</strong>formation out of the function or the subrout<strong>in</strong>e <strong>in</strong>to the call<strong>in</strong>gprogram. Then the parameter is called output parameter.2.10.1 FunctionsThe implementation of a function is given <strong>in</strong> Fortran66/77 as follows.List<strong>in</strong>g 2.21: Syntax of a 66/77-Function1 c2345672 FUNCTION ([])3 []4 []5 = 6 RETURN7 ENDThe implementation of a function is given <strong>in</strong> Fortran90+ as follows. Note that the end of a function isset by the statement end function.List<strong>in</strong>g 2.22: Syntax of a 90-Function1 FUNCTION ([])2 []3 []4 = 5 RETURN6 END FUNCTION []The function Test1 <strong>in</strong> list<strong>in</strong>g 2.23 calculates the function value of a l<strong>in</strong>e. The l<strong>in</strong>es parameter and thex-value are passed by the list of the formal parameters.List<strong>in</strong>g 2.23: A Function and it’s Test<strong>in</strong>g Environment1 ! Ma<strong>in</strong> program as test<strong>in</strong>g environment for function calls2 program functions3 implicit none45 real(8)::Test1 ! function’s return data type6 real(8)::p1,p2,x1 ! the function’s parameters7 real(8)::x0 ! <strong>in</strong>itial value8 real(8)::xD ! <strong>in</strong>crement9 real(8)::t ! function’s value10 <strong>in</strong>teger::i ! loop counter11E. Baeck


2.10. SUBROUTINES AND FUNCTIONS Page 4112 ! <strong>in</strong>itialize x0 and xDel13 x0 = -2.14 xD = 0.251516 ! set function parameters17 p1 = 2.18 p2 = -1.19 x1 = x02021 do i=1,1622 t = Test1(p1,p2,x1) ! calculat<strong>in</strong>g the function value23 write(*,’(2(a,f12.6))’)’ x=’,x1,’ f(x)=’,t24 x1= x1 + xD ! <strong>in</strong>crement the function parameter25 end do2627 end program2829 ! function to calculate some values30 real(8) function Test1(a,b,x)31 implicit none ! we have to declare everyth<strong>in</strong>g explicitly32 real(8)::a,b,x ! declar<strong>in</strong>g the parameters of the function33 Test1 = a*x +b ! calculat<strong>in</strong>g and asign<strong>in</strong>g the return value34 end function Test1 ! the end of function Test12.10.2 Subrout<strong>in</strong>esThe implementation of a subrout<strong>in</strong>e is given <strong>in</strong> Fortran66/77 as follows. You see, there is no return value.The only difference between subrout<strong>in</strong>e and function is the keyword subrout<strong>in</strong>e <strong>in</strong>stead of function, themiss<strong>in</strong>g return type, and the miss<strong>in</strong>g assignment of the return value.List<strong>in</strong>g 2.24: Syntax of a 66/77-Subrout<strong>in</strong>e1 c2345672 SUBROUTINE ([]):3 []4 []5 RETURN6 ENDThe implementation of a subrout<strong>in</strong>e is given <strong>in</strong> Fortran90+ as follows. Note that the end of a subrout<strong>in</strong>eis set by the statement end subrout<strong>in</strong>e.List<strong>in</strong>g 2.25: Syntax of a 90-Subrout<strong>in</strong>e1 SUBROUTINE ([])2 []3 []4 RETURN5 END SUBROUTINE []7.8.2013


Page 42 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 132.10.3 Functions as Parametersif a function should be used as a parameter, the functions should be declared with the return data type andthe attribute external. A typical and nice example is the implementation of Newton’s algorithm to calculatethe roots of an arbitrary equation (see section 3.5). The follow<strong>in</strong>g example shows the implementationof the numerical calculation of a function’s derivative, which is used with<strong>in</strong> the Newton’s algorithm. Thefunction is passed as parameter to the derivative function fs. With<strong>in</strong> the function’s code the function fis declared as a real(8) function. To dist<strong>in</strong>guish a function from a variable the function’s symbolicname should be declared with an external attribute.List<strong>in</strong>g 2.26: Pass<strong>in</strong>g a Function as a Parameter1 function to calculate the deviation of a function2 real(8) function fs (f,x,h)3 real(8), external:: f4 real(8):: x,h5 fs = (f(x +h/2) - f(x -h/2))/h6 end functionSubrout<strong>in</strong>es may also be passed to procedures as call<strong>in</strong>g arguments. if a subrout<strong>in</strong>e is to be passed asa call<strong>in</strong>g argument, it must be declared <strong>in</strong> an external statement. The correspond<strong>in</strong>g dummy argumentshould appear <strong>in</strong> a call statement <strong>in</strong> the procedure.2.11 ArraysAn array is a compound of data of the same type. The items of the array are addressed by an <strong>in</strong>dex value.A static array is declared by the def<strong>in</strong>ition of the data type and the <strong>in</strong>dex range of an array.2.11.1 Static ArrayAn static array is declared <strong>in</strong> Fortran77 with the follow<strong>in</strong>g statements. One really big problem <strong>in</strong> Fortran77is, that there are only static arrays, i.e. the developer has to decide about the size of an array. Ifthe array size is to small, the code must be recompiled. So a Fortran77 software <strong>in</strong> general is not able tofit to the problems size.List<strong>in</strong>g 2.27: Array Declaration <strong>in</strong> 66/771 2 DIMENSION (,,..,)3 ...4 ... or ...5 ...6 (,,..,)In Fortran90 we declare a statical array with the follow<strong>in</strong>g format.List<strong>in</strong>g 2.28: Array Declaration <strong>in</strong> 901 , dimension(,,...,):: E. Baeck


2.11. ARRAYS Page 432.11.2 Dynamical ArrayA dynamical array can be allocated, i.e. created at run time. So first we can evaluate the necessaryarray size and then we can allocate the used memory for the array. This feature is available start<strong>in</strong>g fromFortran90.List<strong>in</strong>g 2.29: Dynamical Array Declaration only <strong>in</strong> 901 , allocatable, dimension(:,:,...,:):: 2 ...3 ... next step we allocate the array4 ...5 allocate((,,...,) [,stat=])6 ...7 ... after the usage we deallocate the memory8 ...9 deallocate(,[stat=])After hav<strong>in</strong>g declared the array name, the array can be allocated by the allocate statement. After theallocation the array items can be accessed. If an array item is accessed before the array is allocated, theprogram <strong>in</strong> general will crash. If the memory of an dynamical array is no longer needed, the array shouldbe deallocated with the deallocate statement.2.11.3 Automatic ArrayAn automatic array will be created automatic <strong>in</strong> a function or <strong>in</strong> a subrout<strong>in</strong>e. If the function or subrout<strong>in</strong>eis exited the automatic array is deallocated automatically. The dimensions of an automatic array arepassed <strong>in</strong>to the function or the subrout<strong>in</strong>e as formal parameters.2.11.4 A little Array ExampleThe follow<strong>in</strong>g code shows how to work with static, dynamic and automatic array.List<strong>in</strong>g 2.30: Static, Dynamic and Automatic Arrays <strong>in</strong> Fortran 901 ! This example shows the 3 types of array available <strong>in</strong>2 ! Fortran 90++3 program Arrays4 implicit none56 <strong>in</strong>teger:: i,j ! loop counter7 <strong>in</strong>teger:: nDim ! used as matrix dimension8 <strong>in</strong>teger:: memstat ! used as memory error flag9 <strong>in</strong>teger:: ioerr ! used as file io error flag10 <strong>in</strong>teger:: ionr = 10 ! channel number11 <strong>in</strong>teger:: nDim1,nDim2 ! dimensions of the matrx <strong>in</strong> file1213 ! if we use functions, we have to declare their retruns14 <strong>in</strong>teger:: iwritemat,ireadmatdim,ireadmat1516 real(8),dimension(3,3)::a ! static array17 real(8),allocatable,dimension(:,:)::b ! dynmical array187.8.2013


Page 44 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1319 character(256)::logname ! name of the output file and <strong>in</strong>put file2021 logname = "arrays.log" ! <strong>in</strong>itialize the filename22 ! note: the file is written <strong>in</strong>to the23 ! projects folder2425 ! open the log file as a new blank file26 open(ionr,file=logname,status=’replace’,iostat=ioerr)27 ! .ne.28 if (ioerr /= 0) then29 write (*,*) ’*** Error: log file not opened!’30 stop31 endif3233 ! allocate the array b, an allocation error ist handled34 nDim = 335 allocate(b(nDim,nDim),stat=memstat)36 if (memstat /= 0) then37 write (*,*) ’*** Error: array b is not allocatable.’38 end if3940 ! allocation check: if b is not allocated, we stop41 if (.not. allocated(b)) then42 write (*,*) ’*** Error: array b not allocated’43 stop44 end if4546 ! <strong>in</strong>itialize array a and b with a special number pattern47 ! - over the rows (1st <strong>in</strong>dex)48 do i=1,34950 ! - over the columns51 do j=1,352 a(i,j) = i*10 +j53 b(i,j) = i*10 +j +100 ! +100, because we want to54 end do ! know, thats the b5556 end do5758 ! pr<strong>in</strong>t array data of a and b to the sceen59 write(*,’(3(f10.3,1x))’) ((a(i,j),j=1,3),i=1,3)60 write(*,’(3(f10.3,1x))’) ((b(i,j),j=1,3),i=1,3)6162 ! and write the array data of a and b <strong>in</strong>to the log file63 ! for later read<strong>in</strong>gs64 ioerr = iwritemat(ionr,a,3,3)65 ioerr = iwritemat(ionr,b,3,3)6667 ! if not longer needed, free the memory of array b68 deallocate(b,stat=memstat)69 ! close log file70 close(ionr)7172 ! open the log file to read the data of the first matrix73 open(ionr,file=logname,status=’old’,iostat=ioerr)74 if (ioerr /= 0) thenE. Baeck


2.11. ARRAYS Page 4575 write(*,*) ’*** Error: file ’,logname,’ not found!’76 stop77 endif7879 ! read the matrix dimension80 if (ireadmatdim(ionr,nDim1,nDim2) == 0) then8182 ! Check the dimensions: size < 1 is not valid83 if (nDim1 < 1 .or. nDim2 < 1) then84 write (*,*) ’*** Error: wrong dimensions ’,nDim1,’ ,’,nDim28586 ! dimensions ok87 else88 ! now we reallocate the array b89 allocate(b(nDim1,nDim2),stat=memstat)90 ! and read the matrix data from the file91 ioerr = ireadmat(ionr,b,nDim1,nDim2)9293 endif9495 else96 ! wrong format -> close the file and stop it97 close(ionr)98 stop99 endif100101 ! close the <strong>in</strong>put file102 close(ionr)103104 ! now we pr<strong>in</strong>t the read data <strong>in</strong>to the screen105 write(*,*) ’Data of the first matrix <strong>in</strong> file:’,logname106 do i=1,nDim1107 write(*,’(10(f10.3,1x))’) (b(i,j),j=1,3)108 enddo109110 ! and deallocate the matrix b111 deallocate(b,stat=memstat)112113 ! the usage of an automatic array of the dimension 4x5114 ! is shown <strong>in</strong> the next call. Only the dimension of the array115 ! ist passed, the array is allocated automatically <strong>in</strong> the116 ! subout<strong>in</strong>e117 call checkautomat(4,5)118119 end program Arrays120121 ! pr<strong>in</strong>t matrix data <strong>in</strong>to a file122 !123 <strong>in</strong>teger function iwritemat(io,m,n1,n2)124 implicit none125126 <strong>in</strong>teger::io ! io channel number127 <strong>in</strong>teger::n1 ! number of rows128 <strong>in</strong>teger::n2 ! number of columns129 real(8), dimension(n1,n2):: m ! matrix data130 <strong>in</strong>teger::ioerr, i, j7.8.2013


Page 46 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13131132 write(io,*,iostat=ioerr) n1,n2 ! write the dimensions133 if (ioerr /= 0) then134 write(*,*) ’*** Error: writ<strong>in</strong>g not possible’135 iwritemat = -1 ! exit, if io error136 return137 endif138139 ! over the rows140 do i=1,n1141 write(io,*) (m(i,j),j=1,n2)142 enddo143144 iwritemat = 0 ! 0 return: everyth<strong>in</strong>g ok145 end function iwritemat146147 ! Read the dimension of a matrix from a file148 <strong>in</strong>teger function ireadmatdim(io,n1,n2)149150 <strong>in</strong>teger::io ! io channel151 <strong>in</strong>teger::n1,n2 ! dimensions of the matrix152 <strong>in</strong>teger::ioerr ! error flag153154 read(io,*,iostat=ioerr) n1,n2155 if (ioerr /= 0) then ! if io-error, perhaps a wrong format156 write(*,*) ’*** Error: wrong file format’157 ireadmatdim = -1158 return159 endif160161 ireadmatdim = 0162 end function ireadmatdim163164 ! read matrix data from a file165 !166 <strong>in</strong>teger function ireadmat(io,m,n1,n2)167 implicit none168169 <strong>in</strong>teger::io ! io channel number170 <strong>in</strong>teger::n1 ! number of rows171 <strong>in</strong>teger::n2 ! number of columns172 real(8), dimension(n1,n2):: m ! matrix data173 <strong>in</strong>teger::ioerr, i, j174175 ! over the rows176 do i=1,n1177 read(io,*,iostat=ioerr) (m(i,j),j=1,n2)178 if (ioerr /= 0) then ! important to check the read-io179 write(*,*)’*** Error: format’180 ireadmat = -1181 return182 endif183 enddo184185 ireadmat = 0186 end function ireadmatE. Baeck


2.11. ARRAYS Page 47187188 ! example for an automic array189 subrout<strong>in</strong>e checkautomat(nDim1,nDim2)190191 real(8), dimension(nDim1,nDim2)::m ! automatic array192193 ! <strong>in</strong>itialize the array with a number pattern194 do i=1,nDim1195 do j=1,nDim2196 m(i,j) = i*10 +j197 enddo198 enddo199200 ! pr<strong>in</strong>t the pattern to the screen201 write(*,*) ’M:’,nDim1,’,’,nDim2202 do i=1,nDim1203 write(*,’(10(f10.3,1x))’) (m(i,j),j=1,nDim2)204 enddo205206 end subrout<strong>in</strong>e2.11.5 Pseudo Dynamic Arrays <strong>in</strong> Fortran 77If we need a dynamic array us<strong>in</strong>g Fortran 77 the only chance to implement this is, to use a static memorybuffer, i.e. a static array which has to be large enough to hold the largest dimension of our pseudodynamic array. How to implement this we can see <strong>in</strong> list<strong>in</strong>g 2.31. The dimension of the vectors are read<strong>in</strong> from a text <strong>in</strong>put file.List<strong>in</strong>g 2.31: Dot Product of Vectors us<strong>in</strong>g a Pseudo Dynamic Array1 c implement<strong>in</strong>g a pseudo dynamic array <strong>in</strong> FORTRAN 772 c3 implicit none45 <strong>in</strong>teger nDim,i6 real*8 GetScalProd7 c memory buffer8 real*8 dBuffer(20)910 c open <strong>in</strong>put file11 open(10,file=’SkalProd.<strong>in</strong>’,status=’old’)12 c13 c read the dimension14 read(10,*) nDim15 c16 c read the first vector17 read(10,*) (dBuffer(i),i=1,nDim)18 c19 c read the second vector20 read(10,*) (dBuffer(i),i=nDim+1,nDim*2)2122 c pr<strong>in</strong>t out23 write(*,*) ’>> scal product of 2 vectors’24 write(*,9000) ’v1 = ’,(dBuffer(i),i=1,nDim)7.8.2013


Page 48 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1325 write(*,9000) ’v2 = ’,(dBuffer(i),i=nDim +1,nDim*2)26 write(*,9000) ’v1*v2 = ’,27 &GetScalProd(dBuffer(1),dBuffer(nDim+1),nDim)28 close(10)29 9000 format(a,20f10.3)30 end3132 c calculation of the dot product of two vectors33 real*8 function GetScalProd(a,b,n)34 implicit none3536 <strong>in</strong>teger i,n37 real*8 a(1),b(1)3839 GetScalProd = 0.40 do 100 i=1,n41 100 GetScalProd = GetScalProd + a(i)*b(i)42 endAs we can see from l<strong>in</strong>e 20 of list<strong>in</strong>g 2.31 the size of the buffer has to be set large enough. If not, the<strong>in</strong>put data will be read <strong>in</strong>to a memory outside of our buffer, which can produce a lot of ugly side effects.The second problem will occur, if the po<strong>in</strong>ter calculation is not perfect (l<strong>in</strong>e 17, 20 and 27). If we use<strong>in</strong>correct po<strong>in</strong>ters, <strong>in</strong>ternal data can be overwritten without provok<strong>in</strong>g any error situation. Side effectslike this are very hard to f<strong>in</strong>d and can be avoided us<strong>in</strong>g allocatable arrays with Fortran 90.E. Baeck


2.12. GLOBAL DATA Page 492.12 Global DataGlobal data <strong>in</strong> Fortran are handled with specific access statements.2.12.1 Classical Fortran and CommonGlobal data <strong>in</strong> Fortran classically are handled with so called common blocks. A common block is ablock of memory, which can be used from all rout<strong>in</strong>es, which are permitted to do this. A rout<strong>in</strong>e will bepermitted to access a common block, if the common block is <strong>in</strong>cluded <strong>in</strong>to this rout<strong>in</strong>e with the statementcommon.Global data can be <strong>in</strong>itialized with the block data statement.List<strong>in</strong>g 2.32: common Block and block data1 c <strong>in</strong>itialization of a common2 c3 c | block data’s name4 block data global56 c name of the common7 c ! | start with longest datatype8 common /old77/ dOld,nOld9 real*8 dOld10 <strong>in</strong>teger nOld1112 data nOld /123/13 data dOld /3.14/1415 endIn list<strong>in</strong>g 2.32 we see, that global data are <strong>in</strong>troduced with a common statement. The name of thecommon <strong>in</strong> this case is old77. If this statement and the follow<strong>in</strong>g declarations (l<strong>in</strong>es 8 to 10) are foundwith<strong>in</strong> a subrout<strong>in</strong>e ore a function, this common variables are available <strong>in</strong> terms of global data.The block data statement, which can be only once <strong>in</strong> a code, will <strong>in</strong>itialize the variables of a commonblock. In this case we assign a value to nOld and dOld.2.12.2 Some Aspects of the Module Concept of Fortran 90Us<strong>in</strong>g Fortran 90, the classical concept of common blocks should be considered as obsolete. Commonblocks can be considered as a source of many possible errors and side effects. With Fortran 90 commonblocks can be substituted by modules.A module <strong>in</strong> Fortran 90 is a compound of data and methods accord<strong>in</strong>g to the object orientated conceptof modern languages. So us<strong>in</strong>g modules we also can develop software <strong>in</strong> Fortran us<strong>in</strong>g modern OOPconcepts. 1111 OOP is discussed later <strong>in</strong> the C++ section, see section 6.10.7.8.2013


Page 50 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13In list<strong>in</strong>g 2.33 some global constants are <strong>in</strong>troduced and <strong>in</strong>itialized. Further a method is implemented<strong>in</strong>side the conta<strong>in</strong>s block, to pr<strong>in</strong>t this constants.List<strong>in</strong>g 2.33: A module to Handle Some Constants1 ! global data <strong>in</strong> FORTRAN 902 ! mak<strong>in</strong>g common and block data obsolete3 module constants45 implicit none67 ! data section8 real, parameter::e = 2.79 character(*), parameter::room = "V15-S03-D03"10 <strong>in</strong>teger ::nrtel= 26131112 ! methodes section13 conta<strong>in</strong>s1415 subrout<strong>in</strong>e pr<strong>in</strong>tConstants1617 write(*,*) "my room..",room18 write(*,*) "my telnr.",nrtel1920 end subrout<strong>in</strong>e pr<strong>in</strong>tConstants2122 end module constants2.12.3 Us<strong>in</strong>g global DataA really big benefit <strong>in</strong> Fortran’s history is, that old Fortran code can be used <strong>in</strong> modern Fortran environmentswith nearly no required changes. This we can see with<strong>in</strong> the next example, which uses theclassical common block of list<strong>in</strong>g 2.32 and the modern module of list<strong>in</strong>g 2.33.List<strong>in</strong>g 2.34: Us<strong>in</strong>g commons and modules1 ! example to show the usage of common and module2 ! with<strong>in</strong> one 90 code3 program GlobalData45 use constants67 implicit none89 ! <strong>in</strong>sert the common-code here10 ! name of the common11 ! | start with longest datatype12 common /old77/ dOld,nOld13 real*8 dOld14 <strong>in</strong>teger nOld1516 ! pr<strong>in</strong>t the global common data17 call pr<strong>in</strong>tGlobals1819 ! change the global common dataE. Baeck


2.12. GLOBAL DATA Page 5120 nOld = 32121 dOld = 4.132223 ! pr<strong>in</strong>t the global common data24 call pr<strong>in</strong>tGlobals25 ! pr<strong>in</strong>t the global module data26 call pr<strong>in</strong>tConstants2728 end program2930 ! subrout<strong>in</strong>e to pr<strong>in</strong>t the common data31 ! to this we have to <strong>in</strong>sert the common code32 subrout<strong>in</strong>e pr<strong>in</strong>tGlobals3334 common /old77/ dOld,nOld35 real*8 dOld36 <strong>in</strong>teger nOld3738 write(*,*) "nOld = ",nOld39 write(*,*) "dOld = ",dOld4041 end subrout<strong>in</strong>e7.8.2013


Page 52 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13E. Baeck


3Some Examples3.1 Hello WorldOne famous application which does n’t make any sense is the program helloworld. There are only twostatements: the first writes the famous text to the screen, the second closes the application.List<strong>in</strong>g 3.1: A Startup Hello1 c234567 702 c comment 123453 write(*,*) "Hello World "4 end3.2 Simple SumThe second example shows the implementation of a simple loop <strong>in</strong> Fortran 66 style. The result of theloop (do-loop with labeled end) is the sum of all <strong>in</strong>tegers from 1 to 10. Each step is pr<strong>in</strong>ted to the screen.∑10S = i (3.1)i=1List<strong>in</strong>g 3.2: Sum up all Numbers from 1 to 101 c2345672 n = 0 ! sum variable, set to zero3 do 100 i=1,10 ! perform<strong>in</strong>g the sum <strong>in</strong> fortran IV style4 n = n + i5 write (*,’(a,i2,a,i4)’) ’ i = ’,i,’ sum = ’,n ! screen dump6 100 cont<strong>in</strong>ue ! end of loop7 end ! end of application53


Page 54 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13The screen output runn<strong>in</strong>g example 3.2 will be the follow<strong>in</strong>g.1 i = 1 sum = 12 i = 2 sum = 33 i = 3 sum = 64 i = 4 sum = 105 i = 5 sum = 156 i = 6 sum = 217 i = 7 sum = 288 i = 8 sum = 369 i = 9 sum = 4510 i = 10 sum = 553.3 Calculation of real*4/8 PrecisionThis example calculates the relative precision of a 4 and 8 byte floatarithmetic. In list<strong>in</strong>g 3.3 a strict 66 cod<strong>in</strong>g is used, if we forget thel<strong>in</strong>e end comment. The idea of this algorithm is, to divide a variable’svalue of 1 by 2 as long as the sum of 1 and this reduced value isgreater than 1. If we would have an <strong>in</strong>f<strong>in</strong>ite precision, this loop wouldbe an endless loop. Because we only have a few digits, this reducedvalue will vanish with some cycles. The last visible value than willbe our relative precision.In figure 3.1 the algorithm to calculate the relative precision is shown.The first part will calculate the relative precision for a 4 byte arithmetic,the second part will calculate the relative precision for the 8byte arithmetic.noStartx 1 = 1.x 2 = 1.d = 2.x 2 = x 2 /ds = x 1 + x 2s = x 1yesresult =x 2 ∗ dStopFigure 3.1: Algorithm’s FlowchartList<strong>in</strong>g 3.3: Calculation of the Arithmetic’s Relative Precision1 C2345678902 real*4 x14, x24, x34, d4 ! variables for real*4 analysis3 real*8 x18, x28, x38, d8 ! variables for real*8 analysis45 c calculation of real*4 relative precision6 x14 = 1.7 x24 = 1.8 d4 = 2.910 100 x24 = x24 /d4 ! back jump label and <strong>in</strong>crement11 x34 = x14 + x24 ! reduction12 c write (*,1001) x34, x24 ! dump is disabledE. Baeck


3.4. RELATIVE PRECISION WITH FUNCTIONS Page 5513 if (x34 .gt. x14) goto 100 ! if <strong>in</strong>crement still seen next run14 x24 = x24 * d415 c output16 write (*,1000) x24 ! pr<strong>in</strong>ts result to screen us<strong>in</strong>g17 ! a format statment (1000)18 1000 format(’ real*4 relative precision: ’,e10.3)19 1001 format(’ x14+x24 = ’,e20.14,’ x24 = ’,e20.14)2021 c calculation of real*8 relative precision22 x18 = 1.23 x28 = 1.24 d8 = 2.25 ! now the same for real*826 200 x28 = x28 /d8 ! arithmetic27 x38 = x18 + x2828 c write (*,2001) x38, x28 ! dump is disabled29 if (x38 .gt. x18) goto 20030 x28 = x28 * d831 c output32 write (*,2000) x283334 2000 format(’ real*8 relative precision: ’,e10.3)35 2001 format(’ x18+x28 = ’,e20.14,’ x28 = ’,e20.14)36 end !If we run this code, we will get the follow<strong>in</strong>g screen output.1 real*4 relative precision: 0.119E-062 real*8 relative precision: 0.222E-15We see, that with 4 byte real we nearly get 7 digits, for a 8 byte real we nearly get 16 digits.3.4 Function to Calculate the Relative PrecisionThe follow<strong>in</strong>g code consists of two rout<strong>in</strong>es, the first is the ma<strong>in</strong> program, which calls the evaluationfunction getRelPrec to get the relative precision. The function is work<strong>in</strong>g with one <strong>in</strong>teger parameter.If the parameter is set to 0, the function evaluates the 4 byte relative precision, if the parameter is set toany value but not 0, the function evaluates the 8 byte relative precision.7.8.2013


Page 56 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13The ma<strong>in</strong> program (l<strong>in</strong>e 1 to 7) is a test<strong>in</strong>g environments and performs the calls. The code of the functionis given start<strong>in</strong>g from l<strong>in</strong>e 9.List<strong>in</strong>g 3.4: Function to Evaluate the Relative Precision for 4 and 8 byte floats1 ! evaluate the relative precision for2 ! 4 and 8 byte float arithmetic3 program getRelPrecMa<strong>in</strong>4 real(8) :: getRelPrec, eps5 write(*,*) ’4 byte relative precision: ’, getRelPrec(0)6 write(*,*) ’8 byte relative precision: ’, getRelPrec(1)7 end program getRelPrecMa<strong>in</strong>89 ! function to calculate the relative precision10 real(8) function getRelPrec(nBytes) ! function <strong>in</strong>terface11 ! return type is real*8, name is getRelPrec12 <strong>in</strong>teger :: nBytes ! nByte: 0:4 bytes / 1:8 bytes13 real(4) :: x14,x24,s4,d4 ! 4 byte data14 real(8) :: x18,x28,s8,d8 ! 8 byte data1516 ! calculation for 4 byte arithmetic17 if (nBytes == 0) then18 x14 = 1.19 x24 = 1.20 d4 = 2.21 do ! implicit loop without a counter22 x24 = x24/d423 s4 = x14+x2424 if (s4


3.5. NEWTON’S ALGORITHM TO CALCULATE A ROOT Page 573.5 Newton’s Algorithm to calculate a RootThe follow<strong>in</strong>g example shows, how to pass a function asa functions parameter. With<strong>in</strong> the Newton’s algorithma root of an equation should be calculated. So we haveto specify the function of <strong>in</strong>terest. The function can beconsidered as an <strong>in</strong>put parameter. The function’s nameis passed to the derivative calculator and to the newtonma<strong>in</strong> rout<strong>in</strong>e.So, if we want to calculate the roots of an equationf (x) = 0, we can apply the iteration scheme 3.3. Thederivative <strong>in</strong> the denom<strong>in</strong>ator is calculated numerically<strong>in</strong> equation 3.2. We see that <strong>in</strong> both equations we needthe values of the function f . This problem can be solvedby pass<strong>in</strong>g the function as a parameter.Figure 3.2: Scheme of the Newton AlgorithmThe derivative - it’s called fs <strong>in</strong> the code - is calculated numerical as follows.f ′ (x) = dfdx ≈ (f (x + h 2 ) − f (x − h 2 ) )/h(3.2)The Newton scheme can be described as follows.x i+1 = x i − f (x)f ′ (x)(3.3)The same formula we get from the triangle of the slope (see figure 3.2) resolv<strong>in</strong>g for x n1 .f ′ (x n ) = f (x n)x n − x n+1(3.4)There are three possible situations to handle with<strong>in</strong> the iteration loop.• The function value is vanish<strong>in</strong>g with respect to our selected precision. The iteration loop will bebroken and the found result is passed back to the caller.• The slope of the function is vanish<strong>in</strong>g. This situation can not be handled by the simple iterationscheme. The iteration will be broken with an error message.• Dur<strong>in</strong>g the iteration each cycle is counted. So the iteration loop will be broken, if the maximumavailable iterations are reached. The actual values and an error message is passed bake to the caller.The code consists of a ma<strong>in</strong> program which calls the function newton. With<strong>in</strong> newton the functionsf and fs are called. Wo we have to implement the follow<strong>in</strong>g functions.• Myf, the function of our <strong>in</strong>terest.• fs, the function which calculates the slope of a given function numerically.7.8.2013


Page 58 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13• newton, implements the newton scheme.The code can be separated <strong>in</strong> two parts or modules. The first module, which is calledNewtonMa<strong>in</strong>.f90, contents the specific code, i.e. the ma<strong>in</strong> program an a test<strong>in</strong>g function. The secondmodule, which is called Newton.f90, contents the newton scheme an the derivative calculator.List<strong>in</strong>g 3.5: Test<strong>in</strong>g Environment to Check the Newton Function1 ! Ma<strong>in</strong> program to test the implementation2 ! of newton’s algorithm34 program NewtonMa<strong>in</strong>5 implicit none67 ! setup the test<strong>in</strong>g parameters8 real(8):: x0 ! start<strong>in</strong>g value9 real(8):: eps ! precision10 <strong>in</strong>teger:: nmax ! maximum number of iterations11 real(8), external:: Myf ! declaration of the function12 <strong>in</strong>teger, external:: newton ! declaration of the newton function1314 <strong>in</strong>teger:: nret ! return of the newton function15 ! solution16 real(8):: x ! root17 real(8):: f0 ! function’s value18 real(8):: fs0 ! slope at root’s position19 <strong>in</strong>teger:: nit ! number of used cycles2021 x0 = 4. ! start<strong>in</strong>g position22 eps = 1.e-6 ! the root’s m<strong>in</strong>imal precison23 nmax= 100 ! available iterations2425 ! pr<strong>in</strong>t <strong>in</strong>put values26 write(*,*) ’ Test program for the newton function’27 write(*,’(A,F12.4)’) ’ Start<strong>in</strong>g value..........: ’,x028 write(*,’(A,E12.5)’) ’ Precision...............: ’,eps29 write(*,’(A,I6)’) ’ Maximum number of cycles: ’,nmax3031 ! the newton is implemented as a function, which returns a status32 ! value. The result values are return by the output parameters33 ! --- <strong>in</strong>put ----- -- output --34 nret = newton(Myf,x0,eps,nmax,x,f0,fs0,nit)3536 ! solution found37 ! .eq. (F66/77)38 if (nret == 0) then ! here we use C-like F90 operators39 write (*,*) ’ Solution found!’4041 ! error: vanish<strong>in</strong>g slope, avoid to divide by zero42 else if (nret == 1) then43 write (*,*) ’ Vanish<strong>in</strong>g slope, no result found!’4445 ! maximum cycles reached. Break to avoid an <strong>in</strong>f<strong>in</strong>it loop46 else47 write (*,*) ’ No solution found, maximum iterations reached!’48 end ifE. Baeck


3.5. NEWTON’S ALGORITHM TO CALCULATE A ROOT Page 594950 ! output section51 write (*,’(A,F15.8)’) ’ Solution value....:’,x52 write (*,’(A,F15.8)’) " Function’s value..:",f053 write (*,’(A,F15.8)’) " Function’s slope..:",fs054 write (*,’(A,I8)’) " Used cycles.......:",nit5556 end program5758 ! user function is an example to tehst newton’s algorithm59 ! This function is passed to the newton function.60 real(8) function Myf(x)61 real(8)::x62 Myf = x**2 -163 return64 end function MyfThe second module contents the more general code, i.e. the code of Newton’s scheme and the derivativescalculator. General it’s recommended to encapsulate the general code 1 <strong>in</strong>to separate modules. Thismodules can also be packed <strong>in</strong>to library files 2 .List<strong>in</strong>g 3.6: Simple Newton Function1 ! implementation of Newton’s algorithm2 <strong>in</strong>teger function newton (f,x0,e,ix,x,fx,fsx,nx)3 implicit none45 real(8), external:: f ! user function6 real(8), external:: fs ! deviation calculator78 real(8)::x0 ! start value9 real(8)::e ! root precision10 real(8)::h ! deviation step width11 real(8)::x ! result: root value12 real(8)::fx ! function’ value at x13 real(8)::fsx ! function’s deviation at x14 <strong>in</strong>teger::ix,nx1516 ! <strong>in</strong>itialization section17 x = x0 ! <strong>in</strong>itialize the iteration variable18 nx = 1 ! iteration counter19 h = e ! set step width for numerical deviation2021 ! iteration loop (note it’s a named loop)22 ma<strong>in</strong>loop: do2324 fx = f(x) ! calculat<strong>in</strong>g the function’s value25 fsx= fs(f,x,h) ! and the function’s solpe2627 ! check the function value, if success return28 if (dabs(fx) < e) then29 newton = 030 return1 This is code, which is general applicable and therefore has no dependence with your application2 A library file contents compiled module code and can be l<strong>in</strong>ked without any compilation to an application.7.8.2013


Page 60 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 133132 ! check the slope, if vanish<strong>in</strong>g return with error33 else if (dabs(fsx) < e) then34 newton = 135 return3637 ! check the number of cycles, if exceeded return with error38 else if (nx == ix) then39 newton = 240 return4142 end if4344 ! calculat<strong>in</strong>g the next x value45 x = x - fx/fsx4647 ! count the cycle48 nx = nx +14950 end do ma<strong>in</strong>loop5152 end function newton5354 ! function to calculate the deviation of a function55 ! note, that a vanish<strong>in</strong>g step width is not handled56 real(8) function fs (f,x,h)57 real(8), external:: f58 real(8):: x,h59 fs = (f(x +h/2) - f(x -h/2))/h60 end functionThe second version of the Newton program will be extended by a function iwritefunction, whichshould pr<strong>in</strong>t the function’s values and the derivative of the function <strong>in</strong> a given range.We extend the ma<strong>in</strong> module by a log file newtonlog.txt and a static array for the iteration path.Before we call the newton function the function iwritefunction will be called to pr<strong>in</strong>t the functionvalues. The allocated array is passed to the newton function to get the iteration path data.List<strong>in</strong>g 3.7: Test<strong>in</strong>g Environment to Check the Newton Function1 ! Ma<strong>in</strong> program to test the implementation2 ! of newton’s algorithm34 program NewtonMa<strong>in</strong>5 implicit none67 ! setup the test<strong>in</strong>g parameters8 real(8):: x0 ! start<strong>in</strong>g value9 real(8):: eps ! precision10 <strong>in</strong>teger:: nmax ! maximum number of iterations11 real(8), external:: Myf ! declaration of the function12 <strong>in</strong>teger, external:: newton ! declaration of the newton function1314 <strong>in</strong>teger:: nret ! return of the newton function15 ! solution16 real(8):: x ! rootE. Baeck


3.5. NEWTON’S ALGORITHM TO CALCULATE A ROOT Page 6117 real(8):: f0 ! function’s value18 real(8):: fs0 ! slope at root’s position19 <strong>in</strong>teger:: nit ! number of used cycles20 character(256)::filename ! name of the log file21 <strong>in</strong>teger::ioerr ! return of the write function22 <strong>in</strong>teger::iwritefunction ! return value of the function2324 ! F66/77 version static array25 real(8), dimension(100)::xp ! iteration path, x values2627 x0 = 0. ! start<strong>in</strong>g position28 eps = 1.e-6 ! the root’s m<strong>in</strong>imal precison29 nmax= 100 ! available iterations3031 filename = ’newtonlog.txt’3233 ! pr<strong>in</strong>t <strong>in</strong>put values34 write(*,*) ’ Test program for the newton function’35 write(*,’(A,F12.4)’) ’ Start<strong>in</strong>g value..........: ’,x036 write(*,’(A,E12.5)’) ’ Precision...............: ’,eps37 write(*,’(A,I6)’) ’ Maximum number of cycles: ’,nmax3839 ! pr<strong>in</strong>t the function’s values <strong>in</strong>to the log file40 ioerr = iwritefunction(filename,Myf,-10.D0,10.D0,0.5D0)41 if (ioerr == 0) then42 write(*,’(a)’) ’ No problems writ<strong>in</strong>g functions values.’43 else44 write(*,’(a,i10)’) " Error writ<strong>in</strong>g function values, code=",ioerr45 endif4647 ! the newton is implemented as a function, which returns a status48 ! value. The result values are return by the output parameters49 ! --- <strong>in</strong>put ----- -- output --50 nret = newton(Myf,x0,eps,nmax,x,f0,fs0,nit,xp)5152 ! solution found53 ! .eq. (F66/77)54 if (nret == 0) then ! here we use C-like F90 operators55 write (*,*) ’ Solution found!’5657 ! error: vanish<strong>in</strong>g slope, avoid to divide by zero58 else if (nret == 1) then59 write (*,*) ’ Vanish<strong>in</strong>g slope, no result found!’6061 ! maximum cycles reached. Break to avoid an <strong>in</strong>f<strong>in</strong>it loop62 else63 write (*,*) ’ No solution found, maximum iterations reached!’64 end if6566 ! output section67 write (*,’(A,F15.8)’) ’ Solution value....:’,x68 write (*,’(A,F15.8)’) " Function’s value..:",f069 write (*,’(A,F15.8)’) " Function’s slope..:",fs070 write (*,’(A,I8)’) " Used cycles.......:",nit71727.8.2013


Page 62 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1373 end program747576 ! user function is an example to tehst newton’s algorithm77 ! This function is passed to the newton function.78 real(8) function Myf(x)79 real(8)::x80 ! Myf = x**2 -1 ! Test 18182 ! Myf = x**2 +1 ! Test 283 Myf = x**3 +1 ! Test 384 return85 end function MyfThe array for the storage of the iteration path data is passed to the newton function. With<strong>in</strong> thema<strong>in</strong>loop the positions on the iteration path are saved <strong>in</strong>to the array xpos. At the end of the modulethe function iwritefunction is added to pr<strong>in</strong>t the function’s values.List<strong>in</strong>g 3.8: Simple Newton Function1 ! implementation of Newton’s algorithm2 <strong>in</strong>teger function newton (f,x0,e,ix,x,fx,fsx,nx,xpos)3 implicit none45 real(8), external:: f ! user function6 real(8), external:: fs ! deviation calculator78 real(8)::x0 ! start value9 real(8)::e ! root precision10 real(8)::h ! deviation step width11 real(8)::x ! result: root value12 real(8)::fx ! function’ value at x13 real(8)::fsx ! function’s deviation at x14 <strong>in</strong>teger::ix,nx15 real(8),dimension(ix)::xpos1617 ! <strong>in</strong>itialization section18 x = x0 ! <strong>in</strong>itialize the iteration variable19 nx = 1 ! iteration counter20 h = e ! set step width for numerical deviation2122 ! iteration loop (note it’s a named loop)23 ma<strong>in</strong>loop: do2425 fx = f(x) ! calculat<strong>in</strong>g the function’s value26 fsx= fs(f,x,h) ! and the function’s solpe2728 ! be sure, that the array is dimensioned properly29 xpos(nx) = x3031 ! check the function value, if success return32 if (dabs(fx) < e) then33 newton = 034 return3536 ! check the slope, if vanish<strong>in</strong>g return with errorE. Baeck


3.5. NEWTON’S ALGORITHM TO CALCULATE A ROOT Page 6337 else if (dabs(fsx) < e) then38 newton = 139 return4041 ! check the number of cycles, if exceeded return with error42 else if (nx == ix) then43 newton = 244 return4546 end if4748 ! calculat<strong>in</strong>g the next x value49 x = x - fx/fsx5051 ! count the cycle52 nx = nx +15354 end do ma<strong>in</strong>loop5556 end function newton5758 ! function to calculate the deviation of a function59 ! note, that a vanish<strong>in</strong>g step width is not handled60 real(8) function fs (f,x,h)61 real(8), external:: f62 real(8):: x,h63 fs = (f(x +h/2) - f(x -h/2))/h64 end function6566 ! write function values to a file67 !68 <strong>in</strong>teger function iwritefunction(name,f,xfrom,xto,xstep)6970 character(256):: name ! files name71 real(8),external::f ! function72 real(8)::xfrom ! start value73 real(8)::xto ! end value74 real(8)::xstep ! step width7576 <strong>in</strong>teger::ioerror ! return status77 real(8)::x ! actual position78 real(8)::h ! step width calculat<strong>in</strong>g the derivative7980 ! check the <strong>in</strong>put parameters81 if (xstep < 1.e-6) then82 write (*,*) ’ *** Error: xstep not ok!’83 iwritefunction = -184 return85 endif8687 ! open the file88 open (10,file=name,status=’replace’,iostat=ioerror)89 if (ioerror .ne. 0) then90 iwritefunction = ioerror91 return ! return if there is an error92 endif7.8.2013


Page 64 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 139394 ! start with the tables header95 ! 12345678901234567890123456789096 write(10,’(a)’)" x f(x) f’(x)"97 write(10,’(a)’)"------------------------------"9899 ! write the function’s values100 h = 1.e-6101 x = xfrom102 do103 write(10,’(3(F10.4))’,iostat=ioerror) x,f(x),fs(f,x,h)104105 ! break the loop, if an error occure106 if (ioerror.ne.0) exit107 x = x + xstep108 if (x > xto) exit109 end do110111 ! close the output file112 close(10)113114 ! return the error code115 iwritefunction = ioerror116117 end function iwritefunctionE. Baeck


3.6. MATRIX PRODUCT WITH 77-MAIN AND 90-LIBRARY Page 653.6 Matrix Product with 77-Ma<strong>in</strong> and 90-LibraryWith<strong>in</strong> this section the mix of Fortran code of version 77 and 90 are discussed. Because <strong>in</strong> Fortran77only static arrays are available, a buffer array is <strong>in</strong>troduced. This array is used for the program memorymanagement.For the three matrices A, B and C , which we use, <strong>in</strong>dex po<strong>in</strong>ters <strong>in</strong>to the buffer array are used formapp<strong>in</strong>g. The dimensions of matrix A and B are read from an <strong>in</strong>put file.The matrix product is calculated accord<strong>in</strong>g to the follow<strong>in</strong>g formula.C = A · B (3.5)with an matrix element C i,jn∑C i,j = A i,k · B k,j (3.6)k=1List<strong>in</strong>g 3.9: 77 Environment to call subsequent Fortran 90 Rout<strong>in</strong>es1 c Fortran77 example to handle a pseudo dynamical memory2 c manager based on a buffer array34 c2345675 <strong>in</strong>teger buffersize ! we use a parameter to6 parameter (buffersize = 100) ! allocate the work buffer7 real*8 buffer(buffersize) ! statical allocation of the buffer89 <strong>in</strong>teger ipA ! po<strong>in</strong>ter of array A10 <strong>in</strong>teger ipB ! po<strong>in</strong>ter of array B11 <strong>in</strong>teger ipC ! po<strong>in</strong>ter of array C1213 <strong>in</strong>teger iret ! return code1415 <strong>in</strong>teger nDimA(2)! Dimension of arra A16 <strong>in</strong>teger nDimB(2)! Dimension of arra B17 <strong>in</strong>teger nDimC(2)! Dimension of arra C1819 <strong>in</strong>teger ionr ! io channel number20 <strong>in</strong>teger ioerr ! error parameter2122 <strong>in</strong>teger ireadmatdim,ireadmat,imatmult2324 character*32 InpFile2526 InpFile = ’MatMult77.<strong>in</strong>p’ ! fixed <strong>in</strong>put file name27 ionr = 102829 c open the <strong>in</strong>put file30 write(*,*) ’> open the file:’,InpFile31 open(ionr,file=InpFile,status=’old’,iostat=ioerr)32 if (ioerr .ne. 0) then33 write(*,*) ’*** Error: open file ’,InpFile34 stop35 endif7.8.2013


Page 66 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 133637 c read dimension of the 1st matrix38 iret = ireadmatdim(ionr,nDimA)39 if (iret .ne. 0) goto 900 ! jump to the error exit40 write(*,*) ’> dimension of array 1 read:’,nDimA(1),’,’,nDimA(2)4142 c read data of array 143 ipA = 144 iret = ireadmat(ionr,buffer(ipA),nDimA)45 if (iret .ne. 0) goto 900 ! jump to the error exit4647 c and list it’s data48 call listmat(’Data of matrix 1:’,buffer(ipA),nDimA)4950 c read dimension of the 2nd matrix51 iret = ireadmatdim(ionr,nDimB)52 if (iret .ne. 0) goto 900 ! jump to the error exit53 write(*,*) ’> dimension of array 2 read:’,nDimB(1),’,’,nDimB(2)5455 c read data of array 256 ipB = ipA + nDimA(1)*nDimA(2)57 iret = ireadmat(ionr,buffer(ipB),nDimB)58 if (iret .ne. 0) goto 900 ! jump to the error exit5960 c and list it’s data61 call listmat(’Data of matrix 2:’,buffer(ipB),nDimB)6263 c multiply matrix 1 with matrix 264 ipC = ipB +nDimB(1)*nDimB(2)65 iret = imatmult(buffer(ipA),buffer(ipB),buffer(ipC),66 & nDimA,nDimB)67 if (iret .ne. 0) then68 write(*,*) ’*** Error: wrong dimensions for product’69 goto 900 ! jump to the error exit70 endif7172 c pr<strong>in</strong>t the result73 nDimC(1) = nDimA(1)74 nDimC(2) = nDimB(2)75 call listmat(’Data of product matrix 1x2:’,buffer(ipC),nDimC)7677 c no problems therefore jump to the regular end78 goto 9997980 c error exit81 900 write(*,*) ’> Programm canceled due to an error!’82 goto 999 ! at last we have to close the <strong>in</strong>put file8384 c close the <strong>in</strong>put file85 999 close(ionr)8687 stop88 endE. Baeck


3.6. MATRIX PRODUCT WITH 77-MAIN AND 90-LIBRARY Page 67With<strong>in</strong> the Fortan 77 code some array functions are called. This functions are coded <strong>in</strong> Fortran 90+. Yousee that us<strong>in</strong>g the new GNU Fortran compiler, it is possible to mix Fortran77 with Fortran 90+ withoutany problems.List<strong>in</strong>g 3.10: 90 Library to Perform a Matrix Product1 ! Note: every read statements reads exactly one l<strong>in</strong>e2 ! empty l<strong>in</strong>es are NOT ignored34 ! read the matrix dimensions5 <strong>in</strong>teger function ireadmatdim(io,nDim)67 <strong>in</strong>teger:: io ! io channel number8 <strong>in</strong>teger, dimension(2):: nDim ! dimension array910 read(io,*,iostat=ioerr) nDim(1),nDim(2)11 if (ioerr /= 0) then ! handle io errors12 write(*,*) ’*** Error: read<strong>in</strong>g dimension data!’13 ireadmatdim = -114 return ! if not ok, then return15 endif1617 ! simple check of the dimensions18 if (nDim(1) < 1 .or. nDim(2) < 1) then19 write(*,*) ’*** Error: <strong>in</strong>valid dimension data:’,nDim(1),’,’,nDim(2)20 ireadmatdim = -221 return22 endif2324 ireadmatdim = 0 ! return code for ok2526 end function ireadmatdim2728 ! function for read<strong>in</strong>g a matrix29 <strong>in</strong>teger function ireadmat(io,a,nDim)3031 <strong>in</strong>teger::io ! io channel number32 <strong>in</strong>teger,dimension(2)::nDim ! declare the dimensions33 real(8),dimension(nDim(1),nDim(2))::a ! array3435 ! over the rows36 do i=1,nDim(1)37 read(io,*,iostat=ioerr) (a(i,j),j=1,nDim(2))3839 if (ioerr /= 0) then ! if an error occure, return40 write(*,*)’*** Error: read<strong>in</strong>g matrix data!’41 ireadmat = -142 return43 endif44 enddo45 ireadmat = 04647 end function ireadmat4849 ! pr<strong>in</strong>t array data to the screen with a comment50 subrout<strong>in</strong>e listmat (comment,a,nDim)7.8.2013


Page 68 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 135152 character*(*) comment ! comment to pr<strong>in</strong>t53 <strong>in</strong>teger, dimension(2)::nDim ! dimension of the matrix54 real(8),dimension(nDim(1),nDim(2))::a ! array data to pr<strong>in</strong>t5556 write(*,*) comment ! write the comment l<strong>in</strong>e5758 ! over the rows59 do i=1,nDim(1)60 write(*,*) (a(i,j),j=1,nDim(2))61 enddo6263 end subrout<strong>in</strong>e listmat6465 ! product of 2 matrices66 <strong>in</strong>teger function imatmult(a,b,c,nDimA,nDimB)6768 <strong>in</strong>teger, dimension(2)::nDimA,nDimB ! declare the dimension arrays69 real(8),dimension(nDimA(1),nDimA(2))::a ! declare array a70 real(8),dimension(nDimB(1),nDimB(2))::b ! declare array b71 real(8),dimension(nDimA(1),nDimB(2))::c ! declare array c7273 ! check the dimension of the matrices74 if (nDimA(2) /= nDimB(1)) then75 imatmult = -176 return77 endif7879 ! calculate the product of the matrices80 ! - over the rows of C81 do i=1,nDimA(1)82 ! - over the columns of c83 do j=1,nDimB(2)84 c(i,j) = 0. ! <strong>in</strong>itialize it85 do k=1,nDimA(2)86 c(i,j) = c(i,j) + a(i,k)*b(k,j)87 enddo88 enddo89 enddo90 imatmult = 09192 end function imatmultIf the ma<strong>in</strong> program is coded <strong>in</strong> Fortran 90+, the application can be much more flexible as if it would becoded <strong>in</strong> Fortran 77, because Fortran90+ allows a build<strong>in</strong> access to the command l<strong>in</strong>e parameters. Thisis not possible by standard cod<strong>in</strong>g with Fortran 77.E. Baeck


4L<strong>in</strong>ear Algebra, Vectors and MatricesThis chapter was written as support for the first lectures only deal<strong>in</strong>g with Fortran 77 development. LaterFortran 90 and C++ were added to the curiculum, so that this chapter can be considered as obsolete withrespect to our current curiculum.4.1 Helper Functions4.1.1 Outl<strong>in</strong>esWith<strong>in</strong> the follow<strong>in</strong>g sections we will discuss some helper functions which we will use to implement thegauss decomposition algorithm and its test<strong>in</strong>g environment.4.1.2 Reset and List a MatrixTo check matrices which are decomposed <strong>in</strong> a lower and upper triangle for example by GaussLU decompositionits helpful to have some helper functions for check<strong>in</strong>g. The helper function ExtractLU extractsthe upper and lower triangle matrix of an arbitrary matrix.If we multiply the upper by the lower matrix we should get the orig<strong>in</strong>al matrix which was decomposed<strong>in</strong> triangles.The follow<strong>in</strong>g new statements are used.• <strong>in</strong>clude 1 , <strong>in</strong>cludes a source code file <strong>in</strong>to a ma<strong>in</strong> file.• dimension 2 , allocates arrays of items of the same data type.• subrout<strong>in</strong>e 3 , declares a subrout<strong>in</strong>e which could be seen as function without return value.• call 4 , a subrout<strong>in</strong>e can be called by the use of the call statement.• read 5 , the read statement is used to read data from keyboard or file.1 <strong>in</strong>clude statement, Page 108, [2]2 dimension statement, Page 51, [2]3 subrout<strong>in</strong>e statement, Page 166, [2]4 call statement, Page 26, [2]5 read statement, Page 145, [2]69


Page 70 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13NameResetMatListMatExtractLUMatMultDiffMatReadDimReadMatWriteMatCommentsResetMat resets the content of a given matrix. The content can be resetedoptionally to the values of a zero matrix and a unity matrixListMat pr<strong>in</strong>ts the values of given matrix <strong>in</strong>to the screen w<strong>in</strong>dow. The valuesof the matrix can be titled with an arbitrary comment str<strong>in</strong>g.ExtractLU extracts the values of a LU-decomposed matrix <strong>in</strong>to a normalizedlower triangle matrix and a upper triangle matrix. This function is necessaryto check the decomposed matrix automatically.MatMult performs the multiplication of two arbitrary matrices whose dimensionsfit to the multiplication algorithm. We use this function to check thedecomposed matrix automatically.DiffMat calculates the difference matrix of two matrices and returns the normof the greatest deference item. This function will be used to check the thedecomposed matrix.ReadDim is used to read the dimension of the matrices from an <strong>in</strong>put file.ReadMat reads the matrix values from a text file. This function is used to importtest values <strong>in</strong>to the test<strong>in</strong>g environment of the decomposition application.WriteMat writes the matrix values to a text file. This function is used to exporttest values from the test<strong>in</strong>g environment of the decomposition application.Table 4.1: Helper FunctionsThe global trace flag is part of the common block def<strong>in</strong>ed <strong>in</strong> the header file trace.h.List<strong>in</strong>g 4.1: Global Data1 c2345672 common /trace/ ntrace ! global flag3 <strong>in</strong>teger*4 ntrace ! def<strong>in</strong>ed <strong>in</strong> a header fileE. Baeck


4.1. HELPER FUNCTIONS Page 71The subrout<strong>in</strong>e ResetMat sets the data of an array optional to zero or to unit matrix.List<strong>in</strong>g 4.2: Reset a Matrix’s Data1 c subrout<strong>in</strong>e to <strong>in</strong>itialize a matrix (n1xn2)2 c if mode = 1 a unit-matrix is set3 c <strong>in</strong> all other cases a zero-matrix is set45 subrout<strong>in</strong>e ResetMat(rm,n1,n2,mode)67 c mode = 0 >> zero-matrix8 c mode = 1 >> unit-matrix910 <strong>in</strong>teger*4 n1, n2 ! matrix dimensions11 <strong>in</strong>teger mode ! reset flag12 real*8 rm(n1,n2) ! declar<strong>in</strong>g the passed matrix1314 c column-<strong>in</strong>dex ! <strong>in</strong> fortran it’s faster to run first15 do i=1,n2 ! over all rows then over all columns1617 c row-<strong>in</strong>dex18 do j=1,n11920 c version 1 with nested ifs21 if (i.eq.j) then22 if (mode.eq.1) then23 rm(j,i) = 1.24 else25 rm(j,i) = 0.26 endif27 else28 rm(j,i) = 0.29 endif3031 c version 2 with only one if without nest<strong>in</strong>g32 c if (i.eq.j .and. mode.eq.1) then33 c a(j,i) = 1.34 c else35 c a(j,i) = 0.36 c endif3738 enddo3940 enddo4142 return43 end7.8.2013


Page 72 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13The subrout<strong>in</strong>e ListMat pr<strong>in</strong>ts the data of a matrix to the console w<strong>in</strong>dow. Besides the data of a matrixthe subrout<strong>in</strong>e should pr<strong>in</strong>t a little title.List<strong>in</strong>g 4.3: List a Matrix’s Data1 subrout<strong>in</strong>e ListMat(com,rm,n1,n2)23 character *(*) com ! *(*) means with variable length4 <strong>in</strong>teger*4 n1, n2 ! matrix dimensions5 real*8 rm(n1,n2) ! matrix to pr<strong>in</strong>t67 c loop over all rows8 write (*,’(a)’) com ! pr<strong>in</strong>t a little title9 do i=1,n1 ! loop over all l<strong>in</strong>es10 ! implicit loop <strong>in</strong> write statement11 write(*,’(10f10.2)’) (rm(i,j),j=1,n2)1213 enddo1415 return16 endTo test the helper subrout<strong>in</strong>es ResetMat and ListMat a ma<strong>in</strong> program should be developed.List<strong>in</strong>g 4.4: Check of previous Rout<strong>in</strong>es1 c2345672 c Ma<strong>in</strong> program for step 13 program matrices145 real*8 a(dim,dim) ! declar<strong>in</strong>g a matrix67 call ResetMat(a,dim,dim,1) ! <strong>in</strong>itialize matrix8 call ListMat(’a-matrix’,a,dim,dim) ! list matrix values to the screen9 read (*,*) i ! read a value1011 endE. Baeck


4.1. HELPER FUNCTIONS Page 734.1.3 LU-Extract, Product and Matrix CompareIn this section we will add some further subrout<strong>in</strong>es and functions to the helper functions library ofsection 4.1.2.If we want to check the LU decompositionA = L · U (4.1)we have to extract the L and U part of a decomposed matrix A x , which holds the upper triangle and thediagonal of the U <strong>in</strong> its upper triangle and it’s diagonal values. The values of the L can extracted formthe lower triangle of A x . Because the L has only 1 values on it’s diagonal, we don’t need to store thisvalues.So we need an extractor subrout<strong>in</strong>e, which creates the L and U matrix. Further we need a subrout<strong>in</strong>efor the multiplication of matrices which is called MatMult. At the end we will need a subrout<strong>in</strong>e whichsearches for the maximum difference of the elements of two matrices which is called DiffMat.The next cod<strong>in</strong>g shows the implementation of the extractor of lower and upper triangle.List<strong>in</strong>g 4.5: Extract the Triangle Data of a Matrix1 subrout<strong>in</strong>e ExtractLU (a,l,u,n)23 c a: result matrix form LU decomposition4 c l: lower triagle extracted to n x n5 c u: upper triagle extracted to n x n6 c n: dimension of a,l,n >> n x n78 <strong>in</strong>teger n9 real*8 a(n,n),l(n,n),u(n,n)1011 c rows12 do i = 1,n1314 c columns15 do j = 1,n1617 c if upper triangle, the lower is set to 0, the18 c upper triangle value is taken19 if (i.lt.j) then20 l(i,j) = 0.21 u(i,j) = a(i,j)2223 c if lower triangle, the upper is set to 0, the24 c lower triangle value is taken25 else if (i.gt.j) then26 u(i,j) = 0.27 l(i,j) = a(i,j)2829 c if diagonale the lower is set to 130 c the diagonale value is assigned to the upper diagonal31 else32 l(i,j) = 1.33 u(i,j) = a(i,j)347.8.2013


Page 74 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1335 endif3637 enddo3839 enddo4041 return42 endTo calculate the orig<strong>in</strong>al matrix which was decomposed, we have to calculate the product of equation4.1. In the first version we only use quadratic matrices.C = A · B (4.2)with an matrix element C i,jn∑C i,j = A i,k · B k,j (4.3)k=1List<strong>in</strong>g 4.6: Product of quadratic Matrices1 subrout<strong>in</strong>e MatMult(a,b,c,n)23 <strong>in</strong>clude ’tracegl.h’ ! give access to common block45 c a: <strong>in</strong>put matrix n x n6 c b: <strong>in</strong>put matrix n x n7 c c: a x b matrix n x n8 c n: dimension of quadratic array910 real*8 a(n,n),b(n,n),c(n,n)1112 ! Trace Code13 if (ntrace.gt.0) write(*,*) ’> MatMult started...’1415 c row <strong>in</strong>dex16 do i=1,n1718 c column <strong>in</strong>dex19 do j=1,n2021 c perform<strong>in</strong>g the scalar product of22 c row vector with column vector23 c but at first we have to <strong>in</strong>itialize the matrix element c(i,j)24 c(i,j) = 0.25 do k=1,n26 c ! remember: ’*’-Operator has greater priority27 ! then ’+’-Operator like <strong>in</strong> mathematics28 c(i,j) = c(i,j) + a(i,k)*b(k,j)2930 end do ! end of k-loop31 enddo ! end of j-loop32 enddo ! end of i-loop3334 ! Trace CodeE. Baeck


4.1. HELPER FUNCTIONS Page 7535 if (ntrace.gt.0) write(*,*) ’> MatMult ended...’3637 return38 endThe function DiffMat calculates the norm of the greatest element of a difference matrix.d = max (|A i,j − B i,j |) (4.4)List<strong>in</strong>g 4.7: Difference Matrix of two Matrices1 real function DiffMat(a,b,n)23 <strong>in</strong>teger n ! dimension of the quadratic matrices4 real*8 a(n,n),b(n,n) ! matrices to analyse56 real*8 d78 c start<strong>in</strong>g value, any of them we use the element (1,1)9 d = dabs(a(1,1) -b(1,1))1011 c rows12 do i=1,n1314 c columns15 do j=1,n1617 c if the next is greater then actual take the next18 if (dabs(a(i,j) -b(i,j)) .gt. d) then19 c dabs(x) calculates the norm of x20 d = dabs(a(i,j) -b(i,j))2122 endif2324 enddo25 enddo2627 DiffMat = d ! the greatest difference value is passed back28 return ! to the call<strong>in</strong>g program29 end7.8.2013


Page 76 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 134.1.4 Matrix Import from Input FileIn this section we want to read data from a <strong>in</strong>put text file and save it to array variables. Therefor weimplement a <strong>in</strong>teger function called ReadMat. We pass the io channel number, the reference to the arrayvariable and its rows and column size. We use the read statement 6 .If there happen any error, the function returns an <strong>in</strong>teger of 1. If no error occur then then function returnsa zero value. This return value can be used <strong>in</strong> a call<strong>in</strong>g code to handle the error situation.List<strong>in</strong>g 4.8: Read Matrix Data from a Text File1 <strong>in</strong>teger function ReadMat(io,rm,n1,n2)23 <strong>in</strong>teger io ! io-chanal no.4 <strong>in</strong>teger n1 ! dimension of rm (rows)5 <strong>in</strong>teger n2 ! dimension of rm (columns)6 real*8 rm(n1,n2) ! matrix78 c row loop9 do i=1,n11011 read (io,*,err=900) (rm(i,j),j=1,n2) ! read row values <strong>in</strong> an implicit12 ! loop13 enddo1415 ReadMat = 0 ! no error16 return ! return to call<strong>in</strong>g program1718 900 ReadMat = 1 ! read<strong>in</strong>g error19 return20 endThe test<strong>in</strong>g environment has the follow<strong>in</strong>g code.We declare the array variable and the used <strong>in</strong>put function ReadMat. Then we open the <strong>in</strong>put file calledmatrices2.<strong>in</strong>p with the open statement 7 . This file is a text file and conta<strong>in</strong>s the matrix element dataseparated by spaces. The rows of the matrix data are separated by l<strong>in</strong>efeeds. The second file is an outputfile. The file will only be created. After hav<strong>in</strong>g read the data, both files will be closed us<strong>in</strong>g the closestatement 8 . If the io-statements are not executed with success the error handler will be activated and willperform a jump to the specified label.6 read statement, Page 145, [2]7 open statement, Page 131, [2]8 close statement, Page 34, [2]E. Baeck


4.1. HELPER FUNCTIONS Page 77List<strong>in</strong>g 4.9: Check<strong>in</strong>g the Matrix IO-Functions1 c2345672 program matrices2 ! def<strong>in</strong><strong>in</strong>g program name for l<strong>in</strong>ker34 <strong>in</strong>teger ReadMat ! declaration of functions5 real*8 a(3,3) ! test matrix6 real*8 r(3) ! test vector78 c io = 5 >>> keyboard9 c io = 6 >>> screen1011 io1 = 10 ! io-number for <strong>in</strong>put12 io2 = 11 ! io-number for output1314 c open files15 open(io1,file=’matrices2.<strong>in</strong>p’,status=’old’,err=900)! open an exist<strong>in</strong>g file16 open(io2,file=’matrices2.out’,status=’unknown’) ! create a new file1718 c Input section19 if (ReadMat(io1,a,3,3) .gt. 0) goto 901 ! read from file20 call ListMat(’matrix values of a’,a,3,3) ! list read data2122 c close files23 800 close(io1,status=’keep’) ! close <strong>in</strong>put file24 close(io2,status=’keep’) ! close output file2526 pause ’press return key...’ ! wait for a look27 stop2829 900 write(*,*) ’ file matrices2.<strong>in</strong>p not found!’30 pause ’press return key...’ ! wait for a look31 stop3233 901 write(*,*) ’ format error, read<strong>in</strong>g matrix a.’34 goto 8003536 end7.8.2013


Page 78 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 134.1.5 Memory Manager and Pseudo Dynamical AllocationIn this section a quasi dynamical memory management approach will be shown. This approach will overcomethe statical declaration of arrays <strong>in</strong> FORTRAN overlay<strong>in</strong>g them with a statical declared memoryblock.After hav<strong>in</strong>g opened the <strong>in</strong>put file matrices3.<strong>in</strong>p (see figure 4.1) we should read the dimension of the firstmatrix from l<strong>in</strong>e 1. This is done by a new helper function which is called ReadDim. With well-knownmatrix dimensions we can request the used memory form the memory manager. With the calculatedmemory block <strong>in</strong>dex the matrix can be read form the file. This is done with the helper function ReadMatof Section 4.1.4.With ReadMat the matrix values are read l<strong>in</strong>e by l<strong>in</strong>e.Figure 4.1: Input data for matrices3After hav<strong>in</strong>g read the matrix data ReadDim is called which read the dimension of the vector, i.e. thedimension of a matrix with only one column. Then the values of the vector are read l<strong>in</strong>e by l<strong>in</strong>e with thefunction ReadMat.List<strong>in</strong>g 4.10: Read Matrix’s Dimension from File1 <strong>in</strong>teger function ReadDim(io,rows,cols)23 <strong>in</strong>teger io, rows, cols45 read (io,*,err=900) rows,cols ! read the dimensionvalues rows and cols6 ReadDim = 0 ! from the <strong>in</strong>put file7 return89 900 ReadDim = 1 ! error branch, error code set if an10 return ! format error is dedected11 endThe ma<strong>in</strong> program Marices3 shows an approach to solve the problem of dynamical memory allocation<strong>in</strong> FORTRAN. Because at last FORTRAN offers only the possibility of statical memory allocation wehave to develop our own memory manager.E. Baeck


4.1. HELPER FUNCTIONS Page 79Therefor a memory block is allocated statically and the used memory of the matrices is overlaid on it.If we want to use the memory we have to calculate the <strong>in</strong>dex of each overlay. We start at the beg<strong>in</strong>n<strong>in</strong>gof the memory block. So the first array will get the <strong>in</strong>dex 1. The <strong>in</strong>dex of the second array is calculatedas the total length of all memory which is already assigned (that means <strong>in</strong> our example the length of thefirst matrix) plus 1. This is the first item of the second matrix.List<strong>in</strong>g 4.11: Check<strong>in</strong>g Matrix Allocation1 c2345672 program Matrices3 ! set the applications name34 <strong>in</strong>teger maxmem ! def<strong>in</strong>e a parameter to allocate5 parameter (maxmem = 1000) ! the memory block statically6 real*8 mem(maxmem) ! memory block78 <strong>in</strong>teger n1,n2,n3,n4 ! matrix/vector dimension9 <strong>in</strong>teger np1 ! position of 1st array10 <strong>in</strong>teger np2 ! position of 1st vector11 <strong>in</strong>teger ReadDim, ReadMat ! declar<strong>in</strong>g the return data type of functions1213 io1 = 10 ! <strong>in</strong>put channel for <strong>in</strong>put file14 np1 = 1 ! position of 1st matrix on memoryblock1516 c open the <strong>in</strong>put file17 open (io1,file=’matrices3.<strong>in</strong>p’,status=’old’,err=900)1819 c read<strong>in</strong>g the dimension of the matrix20 if (ReadDim(io1,n1,n2) .gt. 0) goto 9012122 c read<strong>in</strong>g the dimension of the matrix23 if (ReadMat(io1,mem(np1),n1,n2) .gt. 0)goto 9022425 c write matrix content to output w<strong>in</strong>dow26 call ListMat(’content of 1st matrix’,mem(np1),n1,n2)2728 c read<strong>in</strong>g the dimension of the vector29 if (ReadDim(io1,n3,n4) .gt. 0) goto 9013031 c read<strong>in</strong>g the dimension of the matrix32 np2 = n1*n2 +133 if (ReadMat(io1,mem(np2),n3,n4) .gt. 0)goto 9023435 c write vector content to output w<strong>in</strong>dow36 call ListMat(’content of 1st vector’,mem(np2),n3,n4)3738 c halt a little bit39 pause ’ press return...’40 goto 999 ! jump to the end4142 c error branch for miss<strong>in</strong>g <strong>in</strong>put file43 900 write(*,*) ’ file matrices3.<strong>in</strong>p not found!’44 pause ’ press return...’45 stop4647 c error branch for <strong>in</strong>correct format of dimension l<strong>in</strong>e7.8.2013


Page 80 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1348 901 write(*,*) ’ format error read<strong>in</strong>g the dimension’49 pause ’ press return...’50 stop5152 c error branch for <strong>in</strong>correct format of matrix value l<strong>in</strong>e53 902 write(*,*) ’ format error read<strong>in</strong>g the matrix’54 pause ’ press return...’55 stop5657 c "this is the end"58 999 stop59 endThe output of the program Matrices3 is shown <strong>in</strong> figure 4.2.Figure 4.2: Output screenIn figure 4.3 the memory overlay for our little example are shown. Left-aligned we see the memory ofthe 3x3 matrix and at the right of the matrix we see the memory block of the vector. In our case theparameter memmax must be greater equal 12 to have enough memory to allocate the examples data.Figure 4.3: Memory overlaysE. Baeck


4.1. HELPER FUNCTIONS Page 814.1.6 Automatic Allocation of a Set of MatricesIn this section the ma<strong>in</strong> module of the last example is extended. The error handl<strong>in</strong>g is changed to a morevariable one. The matrices are read with<strong>in</strong> a loop. The memory po<strong>in</strong>ter are calculated step by step basedon the read matrix dimensions.We have added two further vectors to our <strong>in</strong>put data file.Figure 4.4: Input data for matrices3, version 2The code of the ma<strong>in</strong> program is given below.List<strong>in</strong>g 4.12: Check<strong>in</strong>g Automatic Memory Manager1 c2345672 program Matrices3 ! set the applications name34 <strong>in</strong>clude ’tracegl.h’ ! access to global data, common block56 <strong>in</strong>teger maxmem ! def<strong>in</strong>e a parameter to allocate7 parameter (maxmem = 1000) ! the memory block statically8 real*8 mem(maxmem) ! memory block910 <strong>in</strong>teger maxmat ! number of matrices11 parameter (maxmat = 7) ! we want to handle 7 matrices1213 <strong>in</strong>teger nrow(maxmat) ! matrix/vector row dimension14 <strong>in</strong>teger ncol(maxmat) ! matrix/vector column dimension15 <strong>in</strong>teger np(maxmat) ! position of matrix "i"1617 <strong>in</strong>teger nCode ! error-Code of io functions18 character*32 cCode ! error text19 <strong>in</strong>teger ReadDim, ReadMat, ! declar<strong>in</strong>g the return data type of functions7.8.2013


Page 82 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1320 & WriteMat21 io1 = 10 ! <strong>in</strong>put channel number for <strong>in</strong>put file22 io2 = 11 ! output cannel number for output file23 np1 = 1 ! position of 1st matrix on memoryblock2425 c <strong>in</strong>italization of trac<strong>in</strong>g26 ntrace = 0 ! trac<strong>in</strong>g disabled2728 c open the <strong>in</strong>put file29 cCode = ’*** error: <strong>in</strong>put file not found!’30 open (io1,file=’matrices3.<strong>in</strong>p’,status=’old’,err=900)3132 c read trace <strong>in</strong>formation from <strong>in</strong>put file33 c ntrace = 0: trac<strong>in</strong>g disabled34 c ntrace = 1: trac<strong>in</strong>g level one (start/stop of rout<strong>in</strong>es)35 c ntrace = 2: trac<strong>in</strong>g level two (al trace data)36 cCode = ’*** error: trace<strong>in</strong>fo not found!’37 read(io1,*,err=900) ntrace !3839 c open the output file40 cCode = ’*** error: output file could not be created!’41 open (io2,file=’matrices3.out’,status=’unknown’,err=900)4243 c read<strong>in</strong>g the matrix and vector <strong>in</strong>formation of 4 matrices44 do i =1,44546 c setup 1st memory po<strong>in</strong>ter47 if (i.eq.1) then48 np(i) = 14950 c setup momory po<strong>in</strong>ters start<strong>in</strong>g from the 2nd ...51 else52 c previous + length of previous matrix53 np(i) = np(i-1) + nrow(i-1)*ncol(i-1)54 endif5556 c read<strong>in</strong>g the dimension of the matrix57 nCode = ReadDim(io1,nrow(i),ncol(i))58 if (nCode .gt. 0) then59 write (cCode,’(a,i1,a)’) ! setup error <strong>in</strong>formation60 & ’*** error: dimension format of ’,i,’. matrix’61 goto 90062 endif6364 c read<strong>in</strong>g the dimension of the matrix65 nCode = ReadMat(io1,mem(np(i)),nrow(i),ncol(i))66 if (nCode .gt. 0) then67 write (cCode,’(a,i1,a)’) ! setup error <strong>in</strong>formation68 & ’*** error: matrix data format of ’,i,’. matrix’69 goto 90070 endif7172 c write matrix content to output w<strong>in</strong>dow73 write(cCode,’(a,i1,a)’) ’content of ’,i,’. matrix’74 call ListMat(cCode,mem(np(i)),nrow(i),ncol(i))75E. Baeck


4.1. HELPER FUNCTIONS Page 8376 c write matrix content to output file77 nCode = WriteMat(io2,cCode,mem(np(i)),nrow(i),ncol(i))7879 end do8081 c 1. product82 np(5) = np(4) +nrow(4)*ncol(4) ! setup memory for product matrix83 nrow(5)= nrow(1) ! number of rows and columns are given84 ncol(5)= ncol(2) ! by the numbers of the other matrices85 call MatMult(mem(np(1)),mem(np(2)),mem(np(5)),86 & nrow(1),ncol(1),ncol(2))8788 c write matrix content to output w<strong>in</strong>dow89 write(cCode,’(a)’) ’product matrix of a * r1’90 call ListMat(cCode,mem(np(5)),nrow(5),ncol(5))91 nCode = WriteMat(io2,cCode,mem(np(5)),nrow(5),ncol(5))9293 c halt a little bit94 pause ’ press return...’95 goto 999 ! jump to the end9697 c only one error branch, because we have an error text98 900 write(*,*) cCode99 pause ’ press return...’100 stop101102 c "this is the end"103 999 close(io1)104 close(io2)105 stop106 end7.8.2013


Page 84 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure 4.5 shows the output screen of the discussed program. In the do loop the matrices are read fromthe <strong>in</strong>put file and after that the matrix values are written to the screen. The last matrix output shows thevalue of the product of the first and the second matrix. Because the second matrix is the unity vector <strong>in</strong>the first component direction, the result matrix is equal to the first column vector of the first matrix.Figure 4.5: Output ScreenWhats new?• The write statement can also be used to perform formated output to a str<strong>in</strong>g. If we want a formatedoutput to a str<strong>in</strong>g the first parameter - which is usually the io channel number - is used to pass thedest<strong>in</strong>ation str<strong>in</strong>g.List<strong>in</strong>g 4.13: Writ<strong>in</strong>g <strong>in</strong>to a Str<strong>in</strong>g1 write(cCode,’(a,i1,a)’) ’content of ’,i,’. matrix’• As an <strong>in</strong>dex value for the memory po<strong>in</strong>ter we use a <strong>in</strong>dexed array value, mem(np(i)). Thepo<strong>in</strong>ter value np(i) is stored for every used array and is used as an <strong>in</strong>dex value to access thememory block mem.List<strong>in</strong>g 4.14: Allocat<strong>in</strong>g with Memory Po<strong>in</strong>ters1 nCode = ReadMat(io1,mem(np(i)),nrow(i),ncol(i))E. Baeck


4.1. HELPER FUNCTIONS Page 854.1.7 Implement<strong>in</strong>g Trac<strong>in</strong>gIn this section we will implement trac<strong>in</strong>g <strong>in</strong> our example of section 4.1.7. Therefore we <strong>in</strong>troduce a newdata l<strong>in</strong>e <strong>in</strong> our <strong>in</strong>put file. Its only one value with the follow<strong>in</strong>g mean<strong>in</strong>g.0: Trac<strong>in</strong>g is disabled.1: Trac<strong>in</strong>g is enabled. The start and the end of a subrout<strong>in</strong>e or function call is logged on screen.2: Trac<strong>in</strong>g is enabled. An extended Trac<strong>in</strong>g is activated. Values of the called subrout<strong>in</strong>es or functionsare logged on screen too.We have added one further l<strong>in</strong>e at the beg<strong>in</strong>n<strong>in</strong>g of our <strong>in</strong>put data file.Figure 4.6: Input data for matrices3, version 3So we have to <strong>in</strong>troduce a common block as a possibility to access to a global trace flag which is calledntrace. This common block is stored <strong>in</strong> the file tracegl.h and is used by an <strong>in</strong>clude <strong>in</strong> all subrout<strong>in</strong>esand functions which should use trac<strong>in</strong>g.List<strong>in</strong>g 4.15: Global Data tracegl.h1 c2345672 common /trace/ ntrace3 <strong>in</strong>teger ntraceSo we <strong>in</strong>sert the follow<strong>in</strong>g l<strong>in</strong>e of code <strong>in</strong> all subrout<strong>in</strong>es and functions which should have access to thetrace common.List<strong>in</strong>g 4.16: Include the global Data Header1 <strong>in</strong>clude ’tracegl.h’7.8.2013


Page 86 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13To <strong>in</strong>itialize trac<strong>in</strong>g we set a default trace value. We have used disabled trac<strong>in</strong>g, that means a value of 0.Then the first l<strong>in</strong>e should be read from the <strong>in</strong>put file, which contents the trace value. The follow<strong>in</strong>g codeis added to our ma<strong>in</strong> program.List<strong>in</strong>g 4.17: Implement<strong>in</strong>g Trace Functionality, 77 like1 ...2 c <strong>in</strong>italization of trac<strong>in</strong>g3 ntrace = 0 ! trac<strong>in</strong>g disabled4 c open the <strong>in</strong>put file5 cCode = ’ *** error: <strong>in</strong>put file not found!’6 open (io1,file=’matrices3.<strong>in</strong>p’,status=’old’,err=900)7 c read trace <strong>in</strong>formation from <strong>in</strong>put file8 c ntrace = 0: trac<strong>in</strong>g disabled9 c ntrace = 1: trac<strong>in</strong>g level one (start/stop of rout<strong>in</strong>es)10 c ntrace = 2: trac<strong>in</strong>g level two (all trace data)11 cCode = ’ *** error: trace<strong>in</strong>fo not found!’12 read(io1, * ,err=900) ntrace !13 ...To implement trac<strong>in</strong>g <strong>in</strong> our function ReadDim we have to give access to the common block <strong>in</strong>clud<strong>in</strong>gthe common code. Then we can optionally write trace <strong>in</strong>formation to the screen. If ntrace is greater0, we log the beg<strong>in</strong>n<strong>in</strong>g and the end of the rout<strong>in</strong>e. If ntrace is greater 1, we log the read dimensionvalues as well.List<strong>in</strong>g 4.18: Read Matrix’s Dimension from File1 <strong>in</strong>teger function ReadDim(io,rows,cols)23 <strong>in</strong>clude ’tracegl.h’ ! give access to common block45 <strong>in</strong>teger io, rows, cols67 ! Trace Code8 if (ntrace.gt.0) write(*,*) ’> ReadDim started...’910 read (io,*,err=900) rows,cols ! read the dimensionvalues rows and cols1112 ! Trace Code13 if (ntrace.gt.1)14 &write(*,’(a,i3,a,i3)’) ’> rows: ’,rows,’ columns: ’, cols1516 ReadDim = 0 ! from the <strong>in</strong>put file1718 ! Trace Code19 if (ntrace.gt.0) write(*,*) ’> ReadDim ended, no errors...’20 return2122 900 ReadDim = 1 ! error branch, error code set if an2324 ! Trace Code25 if (ntrace.gt.0) write(*,*) ’> ReadDim ended with read error...’26 return ! format error is dedected27 endE. Baeck


4.1. HELPER FUNCTIONS Page 87Like <strong>in</strong> ReadDim we implement trac<strong>in</strong>g also <strong>in</strong> the rout<strong>in</strong>e ReadMat which is given <strong>in</strong> the follow<strong>in</strong>gcode.List<strong>in</strong>g 4.19: Read Matrix’s Data from File1 <strong>in</strong>teger function ReadMat(io,rm,n1,n2)23 <strong>in</strong>clude ’tracegl.h’ ! give access to common block45 <strong>in</strong>teger io ! io-chanal no.6 <strong>in</strong>teger n1 ! dimension of rm (rows)7 <strong>in</strong>teger n2 ! dimension of rm (columns)8 real*8 rm(n1,n2) ! matrix910 ! Trace Code11 if (ntrace.gt.0) write(*,*) ’> ReadMat started...’1213 c row loop14 do i=1,n11516 read (io,*,err=900) (rm(i,j),j=1,n2) ! read row values <strong>in</strong> an implicit17 ! loop18 enddo1920 ReadMat = 0 ! no error2122 ! Trace Code23 if (ntrace.gt.0) write(*,*) ’> ReadMat ended without errors...’24 return ! return to call<strong>in</strong>g program2526 900 ReadMat = 1 ! read<strong>in</strong>g error27 ! Trace Code28 if (ntrace.gt.0) write(*,*) ’> ReadMat ended with read error...’29 return30 end7.8.2013


Page 88 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure 4.7 shows the trace output <strong>in</strong> the output w<strong>in</strong>dow.Figure 4.7: Screen Output with Trac<strong>in</strong>g Level 2E. Baeck


4.2. GAUSS-LU-ALGORITHM Page 894.2 Gauss-LU-Algorithm4.2.1 Gauss Decomposition with Pivot SearchThe follow<strong>in</strong>g l<strong>in</strong>ear equation system is given <strong>in</strong> matrix notation.A · x = b (4.5)If we write it <strong>in</strong> components we will get:⎛⎞ ⎛ ⎞ ⎛ ⎞a n,1 a n,2 . . . a n,na 1,1 a 1,2 . . . a 1,n x 1 b 1a 2,1 a 2,2 . . . a 2,nx .⎜ . . .. ·2b =2. ⎟ ⎜ . . . ⎟ ⎜ . . . ⎟⎝⎠ ⎝ ⎠ ⎝ ⎠x norn∑a ik · x k − b i = 0 (i = 1, 2, ..., n) (4.7)k=1To decompose the matrix A we can use the follow<strong>in</strong>g theorem. 9For a regular matrix A there is a permutation matrix P so that the product P · A can be decomposed<strong>in</strong>to L a lower and U a upper triangle matrix.P · A = L · U (4.8)b n(4.6)If we <strong>in</strong>sert 4.8 <strong>in</strong>to 4.5 after hav<strong>in</strong>g multiplied with P from the left hand side.P · A · x = P · b (4.9)To calculate the solution vector x we <strong>in</strong>troduce the helper vector c.L · U · x = P · b (4.10)L · c = P · b (4.11)With the forward substitution we get the helper vector c. 10 The permutation matrix has to be consideredon the right hand side.L · c = P · b (4.12)With the backward substitution we get the solution vector x. 11R · x = c (4.13)After hav<strong>in</strong>g decomposed the matrix A, forward- backward substitution can be done for as many asdesired right sides. So we can calculate the <strong>in</strong>verse of A column by column with a respective unityvector as right side.A · X = 1 (4.14)9 The proof is given <strong>in</strong> H.R. Schwarz [4] Satz 2.4.10 Forward substitution is possible, because the the vector c is multiplied form the left by a lower triangle matrix.11 backward substitution is possible, because the the vector x is multiplied form the left by an upper triangle matrix.7.8.2013


Page 90 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 134.2.2 Step 1: Memory Manager and Ma<strong>in</strong> ProgramTo handle different data types us<strong>in</strong>g only one memory block we apply the equivalence statement 12 , whichoverlays a set of variables. In our example we overlay the real*8 array dmem and the <strong>in</strong>teger*4 arrayimem.List<strong>in</strong>g 4.20: Setup Memory Manager for GaussLU, 77 like1 c2345672 program GaussLU3 c4 <strong>in</strong>clude ’tracegl.h’56 c memory allocation7 <strong>in</strong>teger*4 mem8X8109 parameter (mem8X = 1000)11 real*8 dmem(mem8X)12 <strong>in</strong>teger*4 imem(1)13 c <strong>in</strong>teger*4 imem(mem8X*2)14 equivalence(dmem(1),imem(1))15 c16 character*32 cCode17 <strong>in</strong>teger*4 nDim ! dimension of matrix a18 <strong>in</strong>teger*4 nLC ! number of load cases (vector b)1920 <strong>in</strong>teger nPA ! po<strong>in</strong>ter for matrix a21 <strong>in</strong>teger nPS ! po<strong>in</strong>ter for scal<strong>in</strong>g vector22 <strong>in</strong>teger nPI ! po<strong>in</strong>ter for permutation vector (<strong>in</strong>teger*4)2324 <strong>in</strong>teger ReadMat ! function return values2526 c <strong>in</strong>itialization27 ntrace = 0 ! no trac<strong>in</strong>g2829 c io - channels30 io1 = 10 ! <strong>in</strong>put31 io2 = 11 ! output3233 c Read <strong>in</strong>put file34 cCode = ’*** error: <strong>in</strong>put file not found!’35 open (io1,file = ’gausslu.<strong>in</strong>p’,status = ’old’,err=900)3637 c read 1st l<strong>in</strong>e38 cCode = ’*** error: format error <strong>in</strong> 1st l<strong>in</strong>e!’39 read (io1,*,err=900) nDim, nLC, ntrace4041 c memory po<strong>in</strong>ter values42 nPA = 143 nPS = nPA + nDim*nDim44 nPI = (nDim*nDim + nDim)*2 +14546 c read the matrix from <strong>in</strong>put file12 equivalence statement, Page 84, [2]E. Baeck


4.2. GAUSS-LU-ALGORITHM Page 9147 nCode = ReadMat(io1,dmem(nPA),nDim,nDim)48 if (nCode .gt. 0) then49 cCode = ’*** error: format error read<strong>in</strong>g matrix’50 goto 90051 endif5253 c close <strong>in</strong>put stream54 close(io1)5556 c list <strong>in</strong>put values57 call ListMat(’Matrix values of A:’,dmem(nPA),nDim,nDim)5859 write(*,’(a,i5)’)’ Po<strong>in</strong>ter of matrix..............:’, nPA60 write(*,’(a,i5)’)’ Po<strong>in</strong>ter of scal<strong>in</strong>g vector......:’, nPS61 write(*,’(a,i5)’)’ Po<strong>in</strong>ter of permutation vector..:’, nPI6263 goto 9996465 c error branch66 900 write(*,*) cCode6768 c end of program69 999 cont<strong>in</strong>ue7071 pause ’press enter....’72 stop73 endThe first <strong>in</strong>put l<strong>in</strong>e sets the dimension of the matrix, the number of the right hand sides and the trace flag.Figure 4.8: Input data7.8.2013


Page 92 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure 4.9 shows the screen output of the first steps ma<strong>in</strong> program. After hav<strong>in</strong>g read the matrix valuesthe matrix values are listed. Then the real*8 po<strong>in</strong>ter <strong>in</strong>dex values of the matrix (1), the scal<strong>in</strong>g vector(3 · 3 + 1 = 10) and the <strong>in</strong>teger*4 po<strong>in</strong>ter <strong>in</strong>dex value ((3 · 3 + 3) ∗ 2 + 1 = 25) are listed.Figure 4.9: Screen output of step 14.2.3 Step 2: Decomposition with Pivot SearchWe encapsulate the Gauss LU decomposition <strong>in</strong> a subrout<strong>in</strong>e of our mathlib module.List<strong>in</strong>g 4.21: GaussLU Decomposition, 77 like1 c Interface description2 c a : matrix to decompose3 c n : dimension of a4 c ip : permutation vector5 c d : scal<strong>in</strong>g vector6 c flag: 0: s<strong>in</strong>gular matrix7 c 1: positiv sign8 c -1: negativ sign9 subrout<strong>in</strong>e gaussLU(a,n,ip,d,flag)10 c11 <strong>in</strong>clude ’tracegl.h’ ! give access to common block12 c13 c declaration14 <strong>in</strong>teger*4 n15 real*8 a(n,n) ! matrix to decompose16 <strong>in</strong>teger*4 ip(n) ! permutation vector17 real*8 d(n) ! scal<strong>in</strong>g vector1819 real*8 s ! helper variables20 real*8 dh21 real*8 dF22 real*8 deps ! precision23 c24 deps = 1.e-725 flag = 126 c27 c (1) build up the scal<strong>in</strong>g vector for pivot search28 c - <strong>in</strong>itialization for row i29 do i=1,n3031 c <strong>in</strong>itialize with orig<strong>in</strong>al row <strong>in</strong>dex32 ip(i) = i33E. Baeck


4.2. GAUSS-LU-ALGORITHM Page 9334 c calcation of sum of all values <strong>in</strong> column j of a35 s = 0.36 do j=1,n37 s = s + dabs(a(i,j))38 end do39 c40 c s = 0 ? if yes, then no regular matrix41 if (s .lt. deps)4243 c matrix s<strong>in</strong>gular return with error flag44 flag = 045 return4647 c48 else4950 c scal<strong>in</strong>g with respect to the column sum51 c value of column i52 d(i) = 1./s5354 endif5556 end do5758 c (2) decomposition59 c - loop over all rows60 do i =1,n-16162 c pivot search63 c - <strong>in</strong>italization:64 dpvt = dabs(a(i,i)*d(i)) ! scaled diagonal value65 ipvt = i ! and its position66 c67 c - no we look at all elements <strong>in</strong> the matrix below68 c the actual diagonal element69 do j=i+1,n70 dh = dabs(a(j,i)*d(j)71 if (dh .gt. dpvt) then ! scaled element is greater then72 dpvt = dh ! actual pivot, we take this value73 ipvt = j ! and its position74 endif75 end do76 c77 c check the pivat ! if pivot is less then precision78 if (dpvt .lt. deps) then ! we have non regular matrix7980 c matrix is s<strong>in</strong>gular => return with error81 flag = 082 return83 end if84 c85 c if neccesary we swap the matrix l<strong>in</strong>es86 c i to pivot-l<strong>in</strong>e87 if (i .ne. ipvt) then8889 flag = -flag ! sign <strong>in</strong>formation for determ<strong>in</strong>ant7.8.2013


Page 94 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1390 ! calculation91 c to swap data, we need a third variable to avoid92 c over writ<strong>in</strong>g!9394 c swap permutation values95 j = ip(i)96 ip(i) = ip(ipvt)97 ip(ipvt)= j9899 c swap scal<strong>in</strong>g factors100 dh = d(i)101 d(i) = d(ipvt)102 d(ipvt) = dh103104 c swap matrix elements of row i and ipvt105 do j = 1,n106 dh = a(i,j)107 a(i,j) = a(ipvt,j)108 a(ipvt,j) = dh109 end do110111 endif112113 c elem<strong>in</strong>ation step114 c for all rows below actual diagonal element115 do j = i+1,n116117 c elim<strong>in</strong>ation factor118 a(j,i) = a(j,i)/a(i,i)119 dF = a(j,i)120 c for all values at the right hand side of the actual121 c diagonal elements column122 do k = i+1,n123 a(j,k) = a(j,k) -dF*a(i,k)124 end do ! end of k-loop column-loop of eleme<strong>in</strong>ation step125126 end do ! end of j-loop row-loop of elem<strong>in</strong>ation step127 end do ! end of i-loop global row-loop128129 return130 endE. Baeck


4.2. GAUSS-LU-ALGORITHM Page 954.2.4 Step 3: Trac<strong>in</strong>g and Memory Po<strong>in</strong>tersWith this step we implement trac<strong>in</strong>g to be able to check the implemented algorithm.4.2.4.1 Trac<strong>in</strong>g the DecomposerTo be able to check the decomposer algorithm we <strong>in</strong>troduce some trac<strong>in</strong>g code <strong>in</strong>to the decomposerrout<strong>in</strong>e gaussLU.We implement the follow<strong>in</strong>g add ons.• We will access to the global variable ntrace of the common-block trace.• We trace the start of gaussLU.• We trace the break of gaussLU, if a s<strong>in</strong>gular matrix is found.• We trace the sum of the norm of all items of a matrix row and it’s <strong>in</strong>verse, the row scal<strong>in</strong>g factor.• Before start<strong>in</strong>g the elim<strong>in</strong>ation step we trace the pivot value and the correspond<strong>in</strong>g matrix row.• If row swapp<strong>in</strong>g is needed, we trace the orig<strong>in</strong>al row <strong>in</strong>dex and the pivot row <strong>in</strong>dex.• We trace the modified matrix elements dur<strong>in</strong>g elim<strong>in</strong>ation.List<strong>in</strong>g 4.22: GaussLU Decomposition with Trac<strong>in</strong>g, 77 like1 c Interface description2 c a : matrix to decompose3 c n : dimension of a4 c ip : permutation vector5 c d : scal<strong>in</strong>g vector6 c flag: 0: s<strong>in</strong>gular matrix7 c 1: positiv sign8 c -1: negativ sign9 subrout<strong>in</strong>e gaussLU(a,n,ip,d,flag)10 c11 <strong>in</strong>clude ’tracegl.h’ ! give access to common block12 c13 c declaration14 <strong>in</strong>teger*4 n15 real*8 a(n,n) ! matrix to decompose16 <strong>in</strong>teger*4 ip(n) ! permutation vector17 real*8 d(n) ! scal<strong>in</strong>g vector18 <strong>in</strong>teger flag ! permutation flag1920 real*8 s ! helper variables21 real*8 dh22 real*8 dF23 real*8 deps ! precision24 c25 deps = 1.e-726 flag = 12728 ! Trace Code7.8.2013


Page 96 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1329 if (ntrace.gt.0) write(*,*) ’> GaussLU started...’30 c31 c (1) build up the scal<strong>in</strong>g vector for pivot search32 c - <strong>in</strong>itialization for row i33 do i=1,n3435 c <strong>in</strong>itialize with orig<strong>in</strong>al row <strong>in</strong>dex36 ip(i) = i3738 c calcation of sum of all values <strong>in</strong> column j of a39 s = 0.40 do j=1,n41 s = s + dabs(a(i,j))42 end do43 c44 c s = 0 ? if yes, then no regular matrix45 if (s .lt. deps) then4647 c matrix s<strong>in</strong>gular return with error flag48 flag = 04950 if (ntrace.gt.0)51 & write(*,*) ’> GaussLU ended with vanish<strong>in</strong>g column...’52 return53 c54 else5556 c scal<strong>in</strong>g with respect to the column sum57 c value of column i58 d(i) = 1./s5960 if (ntrace.gt.1)61 & write (*,’(a,i5,a,e12.5,a,e12.5)’)62 & ’>> row:’,i,’ sum: ’,s,’ scal<strong>in</strong>g value: ’, d(i)6364 endif6566 end do6768 c (2) decomposition69 c - loop over all rows70 do i =1,n-17172 c pivot search73 c - <strong>in</strong>italization:74 dpvt = dabs(a(i,i)*d(i)) ! scaled diagonal value75 ipvt = i ! and its position76 c77 c - no we look at all elements <strong>in</strong> the matrix below78 c the actual diagonal element79 do j=i+1,n80 dh = dabs(a(j,i)*d(j))81 if (dh .gt. dpvt) then ! scaled element is greater then82 dpvt = dh ! actual pivot, we take this value83 ipvt = j ! and its position84 endifE. Baeck


4.2. GAUSS-LU-ALGORITHM Page 9785 end do86 c87 c check the pivat ! if pivot is less then precision88 if (dpvt .lt. deps) then ! we have non regular matrix8990 c matrix is s<strong>in</strong>gular => return with error91 flag = 092 if (ntrace.gt.0)93 & write(*,*) ’> GaussLU ended with vanish<strong>in</strong>g pivot...’94 return95 end if96 c97 if (ntrace.gt.1)98 & write(*,’(a,i5,a,i5,a,e12.5)’)99 & ’>> row:’,i,’ pivot row:’,ipvt,’ pivot value:’,dpvt100101 c102 c if neccesary we swap the matrix l<strong>in</strong>es103 c i to pivot-l<strong>in</strong>e104 if (i .ne. ipvt) then105106 flag = -flag ! sign <strong>in</strong>formation for determ<strong>in</strong>ant107 ! calculation108 c to swap data, we need a third variable to avoid109 c over writ<strong>in</strong>g!110111 c swap permutation values112 j = ip(i)113 ip(i) = ip(ipvt)114 ip(ipvt)= j115116 c swap scal<strong>in</strong>g factors117 dh = d(i)118 d(i) = d(ipvt)119 d(ipvt) = dh120121 c swap matrix elements of row i and ipvt122 do j = 1,n123 dh = a(i,j)124 a(i,j) = a(ipvt,j)125 a(ipvt,j) = dh126 end do127128 if (ntrace.gt.1)129 & write(*,’(a,i5,a,i5)’) ’>> swap of ’,i,’ with ’,ipvt130 endif131132 c elem<strong>in</strong>ation step133 c for all rows below actual diagonal element134 do j = i+1,n135136 c elim<strong>in</strong>ation factor137 a(j,i) = a(j,i)/a(i,i)138 dF = a(j,i)139140 c for all values at the right hand side of the actual7.8.2013


Page 98 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13141 c diagonal elements column142 do k = i+1,n143 a(j,k) = a(j,k) -dF*a(i,k)144 end do ! end of k-loop column-loop of eleme<strong>in</strong>ation step145146 if (ntrace.gt.1)147 & write(*,’(a,i3,a,i3,2x,10e12.3)’)148 & ’ el.step:’,i,’ row:’,j,(a(j,k),k=j,n)149150151 end do ! end of j-loop row-loop of elem<strong>in</strong>ation step152 end do ! end of i-loop global row-loop153154 if (ntrace.gt.0)155 & write(*,*) ’> GaussLU ended with decomposition...’156157 return158 end4.2.4.2 Prepar<strong>in</strong>g the Test EnvironmentTo decompose a matrix us<strong>in</strong>g gaussLU and check the result automatically we need memory for thefollow<strong>in</strong>g arrays.• real*8 array(n,n) AC, the copy of the matrix to decompose.• real*8 array(n,n) A, the matrix to decompose.• <strong>in</strong>teger*4 vector(n) Ip, to store the permutation <strong>in</strong>formation.• real*8 vector(n) S, to store the scal<strong>in</strong>g <strong>in</strong>formation for pivot search.• real*8 array(n,n) L, the lower triangle matrix with zero values <strong>in</strong> the upper triangle.• real*8 array(n,n) U, the upper triangle matrix with zero values <strong>in</strong> the lower triangle.• real*8 array(n,n) AR, the product matrix of lower and upper triangle.After hav<strong>in</strong>g read the <strong>in</strong>put data from the file gausslu.<strong>in</strong>p we copy the matrix values to a backup matrixus<strong>in</strong>g the subrout<strong>in</strong>e MemCpyR8. The helper function MemCpyR8 will be implemented later.After hav<strong>in</strong>g decomposed the matrix A <strong>in</strong>to a lower and upper triangle, the matrices L and U will beextracted us<strong>in</strong>g the helper function extractLU. We now can recalculate the orig<strong>in</strong>al matrix multiply<strong>in</strong>g Land U and swapp<strong>in</strong>g the matrix rows to the orig<strong>in</strong>al positions. In a f<strong>in</strong>al step we calculate the greatestdifference value of the last and the first matrix. If this value vanishes with respect to the used arithmetic(precision) the decomposed matrix is checked.E. Baeck


4.2. GAUSS-LU-ALGORITHM Page 99List<strong>in</strong>g 4.23: Ma<strong>in</strong> Program for GaussLU Decomposition with Trac<strong>in</strong>g1 c2345672 program GaussLU3 c4 <strong>in</strong>clude ’tracegl.h’ ! access to trace common56 c memory allocation7 <strong>in</strong>teger*4 mem8X ! length of memory block <strong>in</strong> *8 units8 parameter (mem8X = 1000)910 real*8 dmem(mem8X) ! memory block11 <strong>in</strong>teger*4 imem(1) ! <strong>in</strong>teger*4 memory12 c <strong>in</strong>teger*4 imem(mem8X*2) ! the same as a above13 equivalence(dmem(1),imem(1))! dmem and imem, the same memory14 c !15 character*32 cCode ! error code str<strong>in</strong>g16 <strong>in</strong>teger*4 nDim ! dimension of matrix a17 <strong>in</strong>teger*4 nLC ! number of load cases (vector b)1819 <strong>in</strong>teger nPA ! po<strong>in</strong>ter for matrix a20 <strong>in</strong>teger nPS ! po<strong>in</strong>ter for scal<strong>in</strong>g vector21 <strong>in</strong>teger nPI ! po<strong>in</strong>ter for permutation vector (<strong>in</strong>teger*4)2223 <strong>in</strong>teger ReadMat ! function return values2425 c <strong>in</strong>itialization26 ntrace = 0 ! no trac<strong>in</strong>g2728 c io - channels29 io1 = 10 ! <strong>in</strong>put30 io2 = 11 ! output3132 c Read <strong>in</strong>put file33 cCode = ’*** error: <strong>in</strong>put file not found!’34 open (io1,file = ’gausslu.<strong>in</strong>p’,status = ’old’,err=900)3536 c read 1st l<strong>in</strong>e37 cCode = ’*** error: format error <strong>in</strong> 1st l<strong>in</strong>e!’38 read (io1,*,err=900) nDim, nLC, ntrace3940 c memory po<strong>in</strong>ter values41 nPA = 1 ! memory po<strong>in</strong>ter of matrix a42 nPS = nPA + nDim*nDim ! memory po<strong>in</strong>ter of scal<strong>in</strong>g vector43 nPI = (nDim*nDim + nDim)*2 +1 ! memory po<strong>in</strong>ter of permutation vector4445 c read the matrix from <strong>in</strong>put file46 nCode = ReadMat(io1,dmem(nPA),nDim,nDim)47 if (nCode .gt. 0) then48 cCode = ’*** error: format error read<strong>in</strong>g matrix’49 goto 90050 endif5152 c close <strong>in</strong>put stream53 close(io1)547.8.2013


Page 100 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1355 c list <strong>in</strong>put values for check<strong>in</strong>g56 call ListMat(’Matrix values of A:’,dmem(nPA),nDim,nDim)5758 write(*,’(a,i5)’)’ Po<strong>in</strong>ter of matrix..............:’, nPA59 write(*,’(a,i5)’)’ Po<strong>in</strong>ter of scal<strong>in</strong>g vector......:’, nPS60 write(*,’(a,i5)’)’ Po<strong>in</strong>ter of permutation vector..:’, nPI61 c62 c save orig<strong>in</strong>al matrix: AC = A63 call MemCpyR8(dmem(1),dmem(nPAC),nDim*nDim)64 c65 c LU-decomposition....: A = (L,U)66 call GaussLU(dmem(1),nDim,imem(nPI),dmem(nPS),flag)67 c68 c Extract.L,U-martices: L = extract(L,U), U= extract(L,U)69 c A L U70 call ExtractLU(dmem(1),dmem(nPL),dmem(nPU),nDim)71 c72 c Product.............: AR = L * U73 call MatMult(dmem(nPL),dmem(nPU),dmem(nPAR),nDim,nDim,nDim)74 c75 c difference of AC and AR76 dif = DiffMat(dmem(nPAC),dmem(nPAR),nDim)7778 if (dif .lt. dEpsR) then79 write (*,*) ’ LU-Decomposition ok!’80 else81 write (*,*) ’ Error <strong>in</strong> LU-Decomposition!’82 endif8384 goto 9998586 c error branch87 900 write(*,*) cCode8889 c end of program90 999 cont<strong>in</strong>ue9192 pause ’press enter....’93 stop94 endE. Baeck


4.2. GAUSS-LU-ALGORITHM Page 101Figure 4.10: Output of gaussLU Trac<strong>in</strong>g4.2.5 Forward-Backward SubstitutionAfter the decomposition (equation 4.8) the solution of a l<strong>in</strong>ear equation system can be calculated us<strong>in</strong>gthe so called forward-backward substitution (equations 4.10, 4.12 and 4.13). Equation 4.12 describes theforward substitution, which calculates the <strong>in</strong>termediate vector b. Equation 4.13 describes the backwardsubstitution, which calculates the result vector x.The code of the forward-backward substitution is given below.List<strong>in</strong>g 4.24: Forward Backward Substitution, 77 like1 c forward / backward substituation2 c3 c a : decomposed4 c n : dimension5 c m : number of load cases6 c ip: permutation vector7 c b : right hand side matrix8 c x : soluton matrix9 subrout<strong>in</strong>e SubstFB(a,n,m,ip,b,x)10 c11 <strong>in</strong>teger n,m12 real*8 a(n,n),b(n,m),x(n,m)13 <strong>in</strong>teger*4 ip(n)1415 c helpers16 real*8 s17 <strong>in</strong>teger ipvt ! orig<strong>in</strong>al row of load item18 c19 c20 c over all right hand sides21 do k=1,m2223 c spectial case dim = 124 if (n.eq.1) then25 x(1,k) = b(1,k)/a(1,1)26 goto 100 ! next load case7.8.2013


Page 102 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1327 endif28 c29 c forward substituation: L*c = P*b30 c31 ipvt = ip(1)32 x(1,k) = b(ipvt,k)3334 do i=2,n35 s = 0.36 do j=1,i-137 s = s + a(i,j)*x(j,k)38 enddo3940 ipvt = ip(i)41 x(i,k) = b(ipvt,k) -s42 enddo43 c44 c backward substituation: U*x = c45 c46 x(n,k) = x(n,k)/a(n,n)4748 do i=n-1,1,-149 s = 0.50 do j=i+1,n51 s = s + a(i,j)*x(j,k)52 enddo5354 x(i,k) = (x(i,k) -s)/a(i,i)55 enddo5657 100 cont<strong>in</strong>ue58 enddo ! end of load case loop5960 return61 end4.2.6 L<strong>in</strong>ear SolverThe solution of a l<strong>in</strong>ear equation system is performed <strong>in</strong> two steps. In a first step the equation matrix isdecomposed by a Gauss-LU decomposer. The second step will be performed for every right hand sidecalculat<strong>in</strong>g the result vector for the selected right hand side.The <strong>in</strong>put data consist of the system dimension, the matrix data and the data of the right hand sides. Anexample is given below.List<strong>in</strong>g 4.25: Inputdata to Read from a Text File1 3 4 2 >> dimension , number of "load cases"2 2.0 1.1 1.3 >> start of matrix data3 0.7 3.0 -0.74 1.3 -3.0 1.55 1.0 0.0 1.0 3.0 >> 4 vectors of right hand side6 0.0 1.0 2.0 2.07 0.0 0.0 3.0 1.0E. Baeck


4.2. GAUSS-LU-ALGORITHM Page 103The ma<strong>in</strong> program implement<strong>in</strong>g the solution of a l<strong>in</strong>ear equation system is given below.List<strong>in</strong>g 4.26: Implementation of a L<strong>in</strong>ear Solver Environment1 C12345672 program L<strong>in</strong>Solve34 <strong>in</strong>clude ’tracegl.h’56 c memory block7 <strong>in</strong>teger*4 mem8X8 parameter (mem8X = 1000)910 c Memory11 real*8 dmem(mem8X)12 <strong>in</strong>teger*4 imem(1)13 c14 equivalence(dmem,imem)15 c16 c system parameters17 <strong>in</strong>teger*4 nDim ! Systemdimension18 <strong>in</strong>teger*4 nLC ! Number of load cases19 <strong>in</strong>teger*4 nFlag ! Permutation sign20 c21 c adress po<strong>in</strong>ter22 <strong>in</strong>teger nPA ! Po<strong>in</strong>ter of A23 <strong>in</strong>teger nPB ! right hand side matrix po<strong>in</strong>ter24 <strong>in</strong>teger nPX ! solution matrix po<strong>in</strong>ter25 <strong>in</strong>teger nPS ! scal<strong>in</strong>g vector po<strong>in</strong>ter26 <strong>in</strong>teger nPAX ! po<strong>in</strong>ter for the product A*X27 <strong>in</strong>teger nPI ! po<strong>in</strong>ter for permutation <strong>in</strong>formation28 c29 <strong>in</strong>teger ReadMat ! declare the functions30 c31 character*32 cCode ! status code32 c33 io1 = 10 ! <strong>in</strong>put channel34 io2 = 11 ! output channel35 ntrace = 036 c37 cCode = ’*** error: <strong>in</strong>put file not found!’38 open (io1,file = ’l<strong>in</strong>solve.<strong>in</strong>p’,status = ’old’,err=900)39 c40 cCode = ’*** error: format error!’41 read(io1,*,err=900) nDim, nLC,ntrace142 c43 nLA = nDim*nDim ! number of items <strong>in</strong> A44 nLB = nDim*nLC ! number of items <strong>in</strong> B,X and A*X45 nLS = nDim ! number of items <strong>in</strong> scal<strong>in</strong>g vector46 c47 c calculation of memory po<strong>in</strong>ters48 nPA = 1 ! po<strong>in</strong>ter of A49 nPB = nLA +1 ! po<strong>in</strong>ter of B50 nPX = nLA +nLB +1 ! po<strong>in</strong>ter of X51 nPS = nLA +2*nLB +1 ! po<strong>in</strong>ter of scal<strong>in</strong>g vector52 nPAX = nLA +2*nLB +nLS +1 ! po<strong>in</strong>ter of the test<strong>in</strong>g matrix A*X7.8.2013


Page 104 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1353 nPI = (nLA +3*nLB +nLS)*2 +1 ! po<strong>in</strong>ter of permutation vector54 c55 c read<strong>in</strong>g <strong>in</strong>put data of A56 nCode = ReadMat(io1,dmem(nPA),nDim,nDim)57 if (nCode .gt. 0) then58 cCode = ’*** error: format of matrix A’59 goto 90060 endif6162 c read<strong>in</strong>g <strong>in</strong>put data of B63 nCode = ReadMat(io1,dmem(nPB),nDim,nLC)64 if (nCode .gt. 0) then65 cCode = ’*** error: format of matrix B’66 goto 90067 endif68 c69 c close <strong>in</strong>put file70 close(io1)7172 c list of decomposed73 call ListMat(’Input matrix:’,dmem(nPA),nDim,nDim)7475 c list of right hand side matrix76 call ListMat(’Right hand sides:’,dmem(nPB),nDim,nLC)77 c78 c decompose A us<strong>in</strong>g Gauss-LU-Decomposition79 call GaussLU(dmem(nPA),nDim,imem(nPI),dmem(nPS),nflag)80 if (nflag.eq.0) then81 write(*,*) ’*** error: matrix A is s<strong>in</strong>gular!’82 goto 99983 endif84 c85 c list of decomposed86 call ListMat(’Decomposed matrix:’,dmem(nPA),nDim,nDim)87 c88 c forward / backward substituation89 call SubstFB (dmem(nPA),nDim,nLC,imem(nPI),dmem(nPB),dmem(nPX))90 c91 c list of solution vectors92 call ListMat(’Solution vectors:’,dmem(nPX),nDim,nLC)93 c94 c jump to the end95 goto 9999697 c error output98 900 write(*,*) cCode99100 c the end101 999 cont<strong>in</strong>ue102 pause ’press enter...’103 stop104 endE. Baeck


4.2. GAUSS-LU-ALGORITHM Page 105Figure 4.11 shows the output w<strong>in</strong>dow of the L<strong>in</strong>Solve program. To check the execution of the programsome test str<strong>in</strong>gs were written to the output screen.Figure 4.11: Outputw<strong>in</strong>dow of L<strong>in</strong>Solve7.8.2013


Page 106 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13E. Baeck


Part IIC/C++107


Page 109C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programm<strong>in</strong>g language.It is regarded as a ”middle-level” language, as it comprises a comb<strong>in</strong>ation of both high-level and low-levellanguage features. It was developed by Bjarne Stroustrup start<strong>in</strong>g <strong>in</strong> 1979 at Bell Labs as an enhancementto the C language and orig<strong>in</strong>ally named C with Classes. It was renamed C++ <strong>in</strong> 1983.As one of the most popular programm<strong>in</strong>g languages ever created, C++ is widely used <strong>in</strong> the software<strong>in</strong>dustry. Some of its application doma<strong>in</strong>s <strong>in</strong>clude systems software, application software, device drivers,embedded software, high-performance server and client applications, and enterta<strong>in</strong>ment software suchas video games. Several groups provide both free and proprietary C++ compiler software, <strong>in</strong>clud<strong>in</strong>g theGNU Project, Microsoft, Intel and Embarcadero Technologies. C++ has greatly <strong>in</strong>fluenced many otherpopular programm<strong>in</strong>g languages, most notably C# and Java.A nice C++ documentation <strong>in</strong> the web you get with the the l<strong>in</strong>k [6].7.8.2013


Page 110 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13E. Baeck


5Development Tools5.1 The Code::Blocks IDEWe have talked a lot about the Code::Blocks IDE <strong>in</strong> section 5.1. For our C/C++ codes we use theCode::Blocks IDE as well. We only need to <strong>in</strong>stall the Fortran version of Code::Blocks, because it’s asimple add on to the orig<strong>in</strong>al one, which is written for C/C++ developments.The only th<strong>in</strong>g we should change develop<strong>in</strong>g C/C++ projects is the selection of the project type and theselection of the compiler. This is discussed below.If we create a new project, to implement C/C++ cod<strong>in</strong>g, we have to select the Consol Application fromthe project creation wizzards template list (see figure 5.1).Figure 5.1: Select<strong>in</strong>g a Console Application, a C/C++-ProjectIf the template is selected, we have to select the standard type of Consol Application, that means we haveto select a C project or a C++ project. Because the C features are also available <strong>in</strong> a C++ development,we select the C++ console application type (see figure 5.2).If we close the console application type, we get the well known start up form for our project (see figure5.3). We have to specify the project’s root folder and the project’s name.With<strong>in</strong> the next step we have to setup the targets. It’s very important to select now the proper compiler.111


Page 112 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure 5.2: Select<strong>in</strong>g of a C++ Console ApplicationFigure 5.3: Select<strong>in</strong>g of a C++ Console ApplicationIn this case it is the GNU C++ compiler, which is called GCC (see figure 5.4).If we click on next, we have completed the creation procedure of a console application. If we openthe project browser an load the code file ma<strong>in</strong>.cpp, we can study the startup code (see figure 5.5). TheHelloCpp node is <strong>in</strong>serted <strong>in</strong>to the project tree, like we have seen <strong>in</strong> the case of Fortran projects. In thecase of C++ project, the code generator creates a file with the name ma<strong>in</strong>.cpp. cpp is used as extensionof C++ files. This extension is important to select the GCC compiler build<strong>in</strong>g the project’s executable.ma<strong>in</strong>.cpp is used, because a C/C++ application needs a ma<strong>in</strong> function. This ma<strong>in</strong> function will be called,if the executable is started.E. Baeck


5.1. THE CODE::BLOCKS IDE Page 113Figure 5.4: Specify<strong>in</strong>g the project targetsFigure 5.5: Startup Code of a C++ Project7.8.2013


Page 114 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13E. Baeck


6Basics of C/C++A detailed description of C and C++ is available <strong>in</strong> literature or can be downloaded from several webpages.6.1 The PrecompilerC and C++ are native languages which are compiled <strong>in</strong>to the native code. Before a code file (cpp-file) iscompiled by the compiler a precompil<strong>in</strong>g step is performed. The precompiler <strong>in</strong>cludes further files <strong>in</strong>toa file or substitutes textually so-called macros, which are def<strong>in</strong>ed <strong>in</strong> terms of precompiler commands. Afurther feature of the precompiler is, the possibility of macro driven optional compil<strong>in</strong>g.Precompiler commands <strong>in</strong> general starts with a # character. In the follow<strong>in</strong>g box <strong>in</strong> the first l<strong>in</strong>e a fileof the development package is <strong>in</strong>cluded. If we use the parenthesis < and > the compiler searches for thefiles first <strong>in</strong> the folders of the compiler packages and then <strong>in</strong> the actual folder. In the second l<strong>in</strong>e the filename is bracketed with the quotes ". Therefore the compiler searches first <strong>in</strong> the aktual folder and then<strong>in</strong> the folders of the development package. With #def<strong>in</strong>e a macro is <strong>in</strong>troduced. With #undef<strong>in</strong>ethe macro can be removed from the macro list. With #ifdef, #else and #endif optional compil<strong>in</strong>gcan be performed. This precompiler commands are work<strong>in</strong>g like the if, else, endif of the Fortrancompiler (section 2.9).List<strong>in</strong>g 6.1: Work<strong>in</strong>g with Macros1 #<strong>in</strong>clude 2 #<strong>in</strong>clude "a_user_file.h"34 #def<strong>in</strong>e MYMACRO5 #ifdef MYMACRO6 ... code, which will be compiled if MYMCRO was def<strong>in</strong>ed7 #else8 ... code, which will be compiled if MYMCRO was not def<strong>in</strong>ed9 #endif115


Page 116 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 136.2 CommentsThe C++ language offers to different comment types. With the classical block comment, which comesform the C language, we can bracket a part of a l<strong>in</strong>e or some l<strong>in</strong>es and make them comments. We startthe comment with /* and close the comment with */. We can put an arbitrary number of characters andl<strong>in</strong>es <strong>in</strong> between this brackets.The second type of comment is a l<strong>in</strong>e end comment. This l<strong>in</strong>e end comment is set with the character //.In the follow<strong>in</strong>g box we see at the beg<strong>in</strong>n<strong>in</strong>g a block comment followed by several l<strong>in</strong>e end comments.The one and only statement of this code <strong>in</strong>cludes the , which is the declaration header ofthe pr<strong>in</strong>tf function, which comes from C and is used by standard to pr<strong>in</strong>t to the screen.List<strong>in</strong>g 6.2: Block- and L<strong>in</strong>e End Comment1 /*2 A little comment example3 (this is a block comment)4 */56 // ... and this is a l<strong>in</strong>e end comment78 // declare the pr<strong>in</strong>tf function9 #<strong>in</strong>clude // compiler searches first <strong>in</strong>10 // the lib folder11 // ".." compiler searches <strong>in</strong> actual folder6.3 Data TypesC/C++ offers the follow<strong>in</strong>g data types, which are also related the the platform.type bytes comment rangechar 2 character or small <strong>in</strong>teger signed: -128 to 127unsigned: 0 to 255short 2 <strong>in</strong>teger number, igned: -32768 to 32767unsigned: 0 to 65535<strong>in</strong>t 4 <strong>in</strong>teger signed: -2147483648 to 2147483647unsigned: 0 to 4294967295long 4 long <strong>in</strong>teger signed: -2147483648 to 2147483647unsigned: 0 to 4294967295float 4 float<strong>in</strong>g po<strong>in</strong>t number. +/- 3.4e +/- 38 ( 7 digits)double 8 double precision float<strong>in</strong>g po<strong>in</strong>t number. +/- 1.7e +/- 308 ( 15 digits)The <strong>in</strong>teger data type can be modified with the unsigned key.E. Baeck


6.4. OPERATORS Page 1176.4 OperatorsC/C++ offers the follow<strong>in</strong>g operators.6.4.1 Assignment Operatoroperator commentexample= Assignment i = 5;6.4.2 Arthmetic Operatorsoperator commentexample+ addition i = 9 +5; ⇒ 14- substraction i = 9 -5; ⇒ 4* multiplication i = 9 *5; ⇒ 45/ division i = 9 /5; ⇒ 1% modulo i = 9 %5; ⇒ 46.4.3 Compound Arithmetic Assignmentoperator commentexample+= addition i = 2; i += 9; ⇒ 11-= substraction i = 3; i -= 1; ⇒ 2*= multiplication i = 2; i *= 4; ⇒ 8/= division i = 6; i /= 2; ⇒ 3%= modulo i = 9; i %= 2; ⇒ 16.4.4 Increment - Decrement Operatorsoperator commentexample++ <strong>in</strong>crementation i = 2; i++; ⇒ 3-- decrementation i = 3; i--; ⇒ 27.8.2013


Page 118 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 136.4.5 Relational and Equality Operatorsoperator commentexample== equal to 3 == 2; ⇒ 0!= not equal to 3 != 2; ⇒ 1> greater 3 > 2; ⇒ 1< less than 3 < 2; ⇒ 0>= greater equal 3 >= 3; ⇒ 1


6.4. OPERATORS Page 1196.4.8 Compound Bitwise Assignmentoperator commentexample&= and i = 0x20; i &= 0xff; ⇒ 0x20|= or i = 0x20; i |= 0xff; ⇒ 0xffˆ= exclusive or i = 0x20; i ˆ= 0xff; ⇒ 0xdf=1; ⇒ 0x106.4.9 Explicit Type Cast<strong>in</strong>g OperatorThe type cast<strong>in</strong>g operator converts one type <strong>in</strong>to another type. The dest<strong>in</strong>ation type is set <strong>in</strong> between tworound brackets. In the follow<strong>in</strong>g example an <strong>in</strong>teger -1 is casted <strong>in</strong>to an unsigned character, so the signbit is no more <strong>in</strong>terpreted as a sign and becomes part of the one byte number <strong>in</strong>formation. Every bit nowis set <strong>in</strong> the one byte variable and therefore we get 255 as value.List<strong>in</strong>g 6.3: Cast<strong>in</strong>g an <strong>in</strong>teger to a unsigned char1 unsigned char i;2 <strong>in</strong>t j = -1;3 k = (unsigned char)j;4 pr<strong>in</strong>tf("k= %d\n",k);56 ... output:7 k= 2556.4.10 sizeof OperatorThe sizeof operator determ<strong>in</strong>es the length of a variable <strong>in</strong> bytes. In the follow<strong>in</strong>g example the length isdeterm<strong>in</strong>ed of an unsigned char, an <strong>in</strong>t, a float and a double. So we get the numbers 1, 4, 4and 8.List<strong>in</strong>g 6.4: Evaluat<strong>in</strong>g the Size with the sizeof Operator1 unsigned char i = 1;2 <strong>in</strong>t j = -1;3 float f = 1.2;4 double d = 3.4;5 pr<strong>in</strong>tf("%d, %d, %d, %d\n",sizeof(i),sizeof(j),sizeof(f),sizeof(d));67 ... output:8 1, 4, 4, 87.8.2013


Page 120 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 136.4.11 Address and Value OperatorThe address operator & determ<strong>in</strong>es the address of a variable <strong>in</strong> memory. The value operator * determ<strong>in</strong>esthe value of data with a given address. In our example we determ<strong>in</strong>e the address of a variable i and thenthe value of the second item of an <strong>in</strong>teger array is determ<strong>in</strong>ed. The address of an array is given by thearrays name. The address of the second item of an array therefore is given by the name of the array plusone.operator commentexample& address pr<strong>in</strong>tf("%X\n",&i); ⇒ 22FF40* value <strong>in</strong>t s[2] = {1,2}; *(s+1); ⇒ 26.5 Tak<strong>in</strong>g about the HelloWe have seen, if we create a new project with<strong>in</strong> Code::Blocks IDE a Hello code is created automatically.From this code we can see how a C/C++ code is buildup.We see from the follow<strong>in</strong>g example code, that a C/C++ application has to have a function, which iscalled ma<strong>in</strong>. A function <strong>in</strong> C/C++ starts the the type of return, <strong>in</strong> this case an <strong>in</strong>t, which is an <strong>in</strong>teger.The type of return is followed by the functions name. In this case the name should be ma<strong>in</strong>, becauseit’s the ma<strong>in</strong> rout<strong>in</strong>e. A function, like <strong>in</strong> Fortran, will have some formal parameters, which are listed <strong>in</strong>between a pair of brackets. In this case we don’t use parameters, therefore the brackets are empty. Thedef<strong>in</strong>ition of the function’s <strong>in</strong>terface is followed by a code block. In C/C++ a code block is enclosedwith<strong>in</strong> curled brackets {...code block...}. Every statement, which is an executable or declar<strong>in</strong>gcode, has to be closed by a semicolon. Therefore <strong>in</strong> general more than one statement can be written <strong>in</strong>toone l<strong>in</strong>e. Note the l<strong>in</strong>e end comments too, which are listed with a green highlight<strong>in</strong>g. We also can see,that a function can be exited with a return statement. If a function should return a value, then the returnstatement is followed by an expression. In this case a value of zero is returned to the operat<strong>in</strong>g system,which is call<strong>in</strong>g the ma<strong>in</strong> function.List<strong>in</strong>g 6.5: Our First Hello1 // declare the iostream2 #<strong>in</strong>clude 34 // setup the namespace5 us<strong>in</strong>g namespace std;67 <strong>in</strong>t ma<strong>in</strong>()8 {9 // stream the str<strong>in</strong>g to the screen10 cout


6.6. A FOR LOOP Page 1216.6 A For LoopThe most used loop statement <strong>in</strong> C/C++ is the for statement. The for statement executes a statement or acode block. The execution of the loop is controlled by tree expressions.List<strong>in</strong>g 6.6: Syntax of a for Loop1 for ([];[];[])2 {3 []4 }• The <strong>in</strong>itialization is executed before the loop is start<strong>in</strong>g.• The break condition is evaluated after each loop cycle. If the value of the expression is vanish<strong>in</strong>gthe loop will be broken, if not a next cycle will be started.• The iteration condition is a statement, which is executed after the execution of a cycle.The follow<strong>in</strong>g example shows how to iterate an <strong>in</strong>teger start<strong>in</strong>g from 5 up to 50 with a step width of5. The first step is to declare and <strong>in</strong>itialize the used variables. We declare them all as <strong>in</strong>t to get 4 byte<strong>in</strong>tegers. After the data type - <strong>in</strong> this case <strong>in</strong>t - the variable optionally can be <strong>in</strong>itialized us<strong>in</strong>g an =operator for the assignment.After we have declared and <strong>in</strong>itialized the variables, a little header l<strong>in</strong>e is pr<strong>in</strong>ted onto the screen with thepr<strong>in</strong>tf function. Here we see, that a constant str<strong>in</strong>g <strong>in</strong> C/C++ is bracketed with double quotes ". A l<strong>in</strong>ebreak character \n uses the so-called escape character \.Then the for loop is started with the for key word and it’s control fields. With<strong>in</strong> the first field the i loopcounter variable is set to the start<strong>in</strong>g value, which we have stored <strong>in</strong> the variable iFrom. The secondfield contents the boolean expression, which should control the cycles. If the loop counter i is less equalthe end value, which is stored <strong>in</strong> the variable iTo a next cycle is started. Here we use the operator


Page 122 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 131213 // note: every statement has to be closed by an ’;’ character1415 <strong>in</strong>t ma<strong>in</strong>()16 {17 <strong>in</strong>t i; // note: there is no implicit declaration18 <strong>in</strong>t iFrom = 5; // here we use an <strong>in</strong>teger datatype19 <strong>in</strong>t iTo = 50;20 <strong>in</strong>t iStep = 5;2122 // "\n" : l<strong>in</strong>e break23 // pr<strong>in</strong>tf is the standard C pr<strong>in</strong>t rout<strong>in</strong>e, which is declared24 // with<strong>in</strong> the stdio.h file of the standard C library25 pr<strong>in</strong>tf("This is a Loop Application\n");2627 // run a loop28 for (i=iFrom;i


6.7. STATIC ARRAYS Page 1236.7 Static ArraysIn this section we will see how to allocate static arrays <strong>in</strong> C/C++. A static array is like <strong>in</strong> Fortran asequence of data of the same data type. The data with<strong>in</strong> the array are accessed by an <strong>in</strong>dex. A veryimportant difference between C/C++ and Fortran is, that the first <strong>in</strong>dex of an array <strong>in</strong> C/C++ is zero anda standard array <strong>in</strong> Fortran starts with the <strong>in</strong>dex one.So if we mix Fortran and C/C++ code we should be very careful with the array <strong>in</strong>dex<strong>in</strong>g. To show theusage of static arrays we will discuss a little example, which calculates the scalar product of two vectors,which are represented <strong>in</strong> the code by two arrays.An array <strong>in</strong> C/C++ is declared by the data type followed by the arrays name and the arrays dimension.List<strong>in</strong>g 6.8: Declaration of a Static Array1 [ [,]...[,] ];In our example we use two array with one <strong>in</strong>dex and it’s dimension of 3. The data type should be a largefloat which <strong>in</strong> C/C++ is called double.With<strong>in</strong> the first part our example declares and <strong>in</strong>itializes the vectors and the result variable sp. If anarray should be <strong>in</strong>itialized, a list of values separated by commas and bracketed <strong>in</strong>to curled brackets isassigned to the arrays name. Then the result is calculated with<strong>in</strong> a for loop, which runs over all vectoritems. See also equation 6.1, which describes how to calculate the scalar product of two vectors ⃗a and ⃗ b.The loop counter is <strong>in</strong>itialized with zero, the first array <strong>in</strong>dex. The loop runs up to the <strong>in</strong>dex 2, which isthe last valid array <strong>in</strong>dex. After each cycle the counter i is <strong>in</strong>cremented with the <strong>in</strong>crementation operator++.s = ⃗a · ⃗bn∑= a i · b i (6.1)i=1After hav<strong>in</strong>g calculated the scalar product the result is pr<strong>in</strong>ted to the screen with the pr<strong>in</strong>tf function. Inthis case we use the escape %10.3f. The first number sets the width of the output field, <strong>in</strong> this case 10character. The second number sets the decimal places.List<strong>in</strong>g 6.9: Multiply<strong>in</strong>g Vectors by a Dot Product1 // declare the pr<strong>in</strong>tf function2 #<strong>in</strong>clude 34 <strong>in</strong>t ma<strong>in</strong>()5 {6 <strong>in</strong>t i; // loop counter7 double s1[3] = {1.1,1.2,1.3}; // vector 18 double s2[3] = {2.1,2.2,2.3}; // vector 29 double sp = 0.; // scalar product1011 // calculate the scalar product12 sp = 0.; // you should <strong>in</strong>itialize everyth<strong>in</strong>g13 for (i=0;i


Page 124 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1318 // pr<strong>in</strong>t the result19 pr<strong>in</strong>tf("s1*s2 = %10.3f\n",sp); // pr<strong>in</strong>t the result2021 // pr<strong>in</strong>t the addresses of the arrays. If we do this, the address22 // should be casted to an unsigned <strong>in</strong>teger value23 // - this is an cast operator: new = (datatype)old24 // it converts the old <strong>in</strong>to the new25 pr<strong>in</strong>tf("address of s1: %X\n",(unsigned <strong>in</strong>t)s1);26 pr<strong>in</strong>tf("address of s2: %X\n",(unsigned <strong>in</strong>t)s2);2728 // calculate the scalar product29 // us<strong>in</strong>g item po<strong>in</strong>ters, i.e. the address of the data <strong>in</strong> memory30 //31 // s1 is the address of the first item <strong>in</strong> the array s132 // so we add up the <strong>in</strong>dex value [0..2] and get all the values33 // of the array. The * - operator gets the value which is stored34 // at the given address35 sp = 0.;36 for (i=0;i


6.8. BRANCHING Page 1256.8 Branch<strong>in</strong>gLike <strong>in</strong> Fortran too C/C++ provides some statements for branch<strong>in</strong>g. The most used and most commonbranch<strong>in</strong>g statement is the if..else if..else statement. The if is followed by an expression.If the expression’s value is zero the assigned code block is not executed. If the expression’s value isnot vanish<strong>in</strong>g the code block is executed. Optionally we can extend the first if by further else ifconditions. At the end an optional else can be <strong>in</strong>troduced with it’s own code block.List<strong>in</strong>g 6.10: Syntax of the if Statement1 if ([expression 1]) code block 12 else if ([expression 2]) code block 23 else if ([expression 3]) code block 34 ...5 else code block nThe follow<strong>in</strong>g example shows the usage of the if..else if..else statement and the usage of someoperators, which are discussed <strong>in</strong> section 6.4.List<strong>in</strong>g 6.11: Simple Operator Example Us<strong>in</strong>g if1 /*2 Example to discuss some C/C++ operators3 */45 // this we need for pr<strong>in</strong>tf6 #<strong>in</strong>clude 78 <strong>in</strong>t ma<strong>in</strong>()9 {10 <strong>in</strong>t i=2, j=-2; // two number11 <strong>in</strong>t flag; // and a flag1213 // compare two numbers14 // 1st if15 if (i == j) pr<strong>in</strong>tf("%d is equal %d\n",i,j);16 // 2nd if17 else if (i == -j) pr<strong>in</strong>tf("%d is equal m<strong>in</strong>us %d\n",i,j);18 // ... and the else branch19 else20 {21 pr<strong>in</strong>tf("no if executed!\n");22 pr<strong>in</strong>tf("i = %d, j = %d\n",i,j);23 }2425 // here we use the not equal operator26 if (i != j) pr<strong>in</strong>tf("%d is not equal %d\n",i,j);2728 // now there are some very useful bit operators29 flag = 0;3031 // set the 20th bit, coded <strong>in</strong> a hexdecimal number32 flag |= 0x00080000; // 4 byte number3334 // we pr<strong>in</strong>t the number first <strong>in</strong> hex and then <strong>in</strong> decimal7.8.2013


Page 126 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1335 pr<strong>in</strong>tf("flag = 0x%8.8X - %d\n",flag,flag);3637 // the 20th bit is set and all bits of the lower 2 bytes.38 // (if we set all bits we can simple use the F digit)39 flag |= 0x0008FFFF; // 4 byte number4041 // to clear the 2nd bit we first code it <strong>in</strong> hex 0x0242 // and then <strong>in</strong>vert it with the ˜ operator. Then the <strong>in</strong>verse43 // of the second is overlayed bit by bit with the and operator &44 flag &= ˜0x2;4546 // the result is pr<strong>in</strong>ted to the screen47 pr<strong>in</strong>tf("flag = 0x%8.8X - %d , <strong>in</strong>verted 2nd bit: 0x%8.8X\n",flag,flag,˜0x2);48 }E. Baeck


6.9. EXCEPTIONS Page 1276.9 ExceptionsThe classical error handl<strong>in</strong>g is work<strong>in</strong>g with return codes, i.e. a function is called and will return a code(mostly a number), to show whether the the function had success or not. If we only have a very flatcall<strong>in</strong>g hierarchy, this is not a big work to implement. But if we have a lot of functions to call, the wayback to the master call can be very difficult.So <strong>in</strong> modern languages so called error handlers have been implemented, which are work<strong>in</strong>g similar toevent handlers, i.e. an error event is created, the function is canceled and the error handler is search<strong>in</strong>gfor a goal to cont<strong>in</strong>ue with the work. An error event like this is called an exception. The exception willbe thrown <strong>in</strong> the case on an error.The error event handler is enabled, if we put the code, which can produce exceptions <strong>in</strong>to an try block.So, if an error occur <strong>in</strong> this try block, the error event handler is search<strong>in</strong>g for a snipped of code, whichshould treat this event. This codes are put <strong>in</strong>to so called catch blocks, which should catch a thrownexception.So the syntax of this error handl<strong>in</strong>g is as follows.List<strong>in</strong>g 6.12: Syntax of the if Statement1 // enabl<strong>in</strong>g error handl<strong>in</strong>g2 try3 {4 ... // this code should be executed with an error handler5 }6 // catch block with exception data7 catch( )8 {9 ... // error code for a specified exception10 }11 // at the end all unspecified exceptions are handled12 catch(...)13 {14 ... // error code for all unspecified exceptions15 }The follow<strong>in</strong>g example shows how to throw an exception. In l<strong>in</strong>e 8 an <strong>in</strong>teger exception is thrown withthe code 123. So the try code is aborted <strong>in</strong> this l<strong>in</strong>e and the catch block <strong>in</strong> l<strong>in</strong>e 23 is executed. If we wouldset the first throw an comment, the second would throw an const char* exception, which passes asimple C str<strong>in</strong>g. In this case the catch block start<strong>in</strong>g at l<strong>in</strong>e 17 would be executed.List<strong>in</strong>g 6.13: Simple Exception Example1 #<strong>in</strong>clude 2 <strong>in</strong>t ma<strong>in</strong>()3 {4 // try to do someth<strong>in</strong>g5 try6 {7 // create an <strong>in</strong>teger exception8 throw 123;910 // create a str<strong>in</strong>g exception11 throw "*** kill the startup!";7.8.2013


Page 128 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 131213 pr<strong>in</strong>tf("some unreachable statements....\n");14 }1516 // catch the exception, if someth<strong>in</strong>g is wrong#<strong>in</strong>clude "node.h"17 catch(const char* str)18 {19 pr<strong>in</strong>tf("*** Exception: ’%s’\n",str);20 }2122 // catch an <strong>in</strong>t exception23 catch(<strong>in</strong>t nCode)24 {25 pr<strong>in</strong>tf("*** Exception: %d\n",nCode);26 }27 // catch everyth<strong>in</strong>g28 catch(...)29 {30 pr<strong>in</strong>tf("typeless exception\n");3132 }33 return 0;34 }The program’s output isshown <strong>in</strong> figure 6.3.We can see the format of the<strong>in</strong>teger catch block with thedata of the throw<strong>in</strong>g statement123.Figure 6.3: Output of the Exception ExampleE. Baeck


6.10. OOP WITH CLASSES Page 1296.10 OOP with ClassesC++ is an object orientated program<strong>in</strong>g language 1 . So what is the concept of an object or a class? Aclass or an object comb<strong>in</strong>es data, called attributes, with functions, called methods. This can be describedby so called UML 2An <strong>in</strong>stance of a class, that is the realization of the class <strong>in</strong> memory, is created simply by assign<strong>in</strong>g theclass’s name followed by the constructors parameter list to a symbolic name, which than is the po<strong>in</strong>ter orthe reference to this <strong>in</strong>stance. To access member attributes or methods of a class the dot notation is used,i.e. .. The <strong>in</strong>stance will be deleted if it runs out of scope.6.10.1 Some UML DiagramsUML structure diagrams of the emphasize the th<strong>in</strong>gs that must be present <strong>in</strong> the system be<strong>in</strong>g modeled.S<strong>in</strong>ce structure diagrams represent the structure they are used extensively <strong>in</strong> document<strong>in</strong>g the architectureof software systems. In our description of the examples we want to implement we use the ClassDiagram which describes the structure of a system by show<strong>in</strong>g the system’s classes, their attributes, andthe relationships among the classes.A UML class diagram (see figure 6.4) consists of a rectangular box, which is divided<strong>in</strong>to three sections. The fist section contents the class’s name. This nameis written centered <strong>in</strong> bold letters. The second section contents the attribute’snames of the class and the third section contents the method’s names.Class Nameattribute 1attribute 2method 1method 2Figure 6.4: A UMLClass DiagramA UML note diagram (see figure 6.5) consists of a stylized note sheet which isfilled with some <strong>in</strong>formation.Class Nameattribute 1attribute 2method 1method 2This isClass 1This is onlya simple NoteFigure 6.5: A UML NoteDiagramA UML note diagram (see figure 6.6) will be assigned to another component of the diagram scene with a simple l<strong>in</strong>e.Figure 6.6: A UML Note Diagram AssignmentFigure 6.7 shows how to draw diagrams for <strong>in</strong>herit<strong>in</strong>g classes. An arrow witha white filled arrowhead po<strong>in</strong>ts from the <strong>in</strong>herit<strong>in</strong>g class, the special class, tothe <strong>in</strong>herited class, the base class. The attributes and the methods of the Baseclass are now available <strong>in</strong> the name space of the <strong>in</strong>herit<strong>in</strong>g class, i.e. the specialclass now has the attributes attributB1, attributB2, attributS1 andattributS2.Base ClassattributeB1attributeB2methodB1methodB2Special ClassattributeS1attributeS2methodS1methodS21 Object orientated Programm<strong>in</strong>g is often used with the abbreviation OOP.Figure 6.7: A UML Inheritanceof software-<strong>in</strong>tensiveDiagram2 The Unified Model<strong>in</strong>g Language <strong>in</strong>cludes a set of graphic notation techniques to create visual modelssystems. The Unified Model<strong>in</strong>g Language is an <strong>in</strong>ternational standard see [7], UML 2.3 was formally released <strong>in</strong> May 2010.7.8.2013


Page 130 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Class 1List AList Bmethod 1Class Aattribute A1attribute A2method A12..**Class Battribute B1attribute B2method B1..*Figure 6.8: A UML Diagram for a Composition andan AggregationFigure 6.8 shows a aggregation and a composition.An aggregation is drawn by a white filled rhombus.An composition is drawn by a black filled rhombus.Aggregation and compositions describe a conta<strong>in</strong>eror a list of several <strong>in</strong>stances of an object, which aremembers of a ma<strong>in</strong> class. If for example a profileconsists of several parts, the parts can be described asan composition, if a part only exists with<strong>in</strong> a profile.If a part exists also without a profile, the parts aredescribed with<strong>in</strong> the profile with an aggregation.At the ends of the connect<strong>in</strong>g l<strong>in</strong>es the multiplicitiesare noted. The multiplicity gives the range of referenced<strong>in</strong>stances <strong>in</strong> the form from..to. For the Class Awe have 2 up to <strong>in</strong>f<strong>in</strong>ite <strong>in</strong>stances <strong>in</strong> an composition,therefor at the end of the l<strong>in</strong>e we can not have a multiplicityof zero. In our example we have exactly one <strong>in</strong>stance of the class 1. On the other hand Class Bis referred to Class 1 with<strong>in</strong> an aggregation. In our example on <strong>in</strong>stance of Class B can be reverenced byan undef<strong>in</strong>ed number of <strong>in</strong>stances of Class 1. This is shown by the * icon. On the other hand the class1 references at least on <strong>in</strong>stance of the Class B. Otherwise the number of references is arbitrary. This isalso shown by the * icon.6.10.2 C++ ClassA C++ class consists of a declaration and an implementation part. The declaration part often lives <strong>in</strong> aheader file with the class’s name as prefix and h as suffix. The implementation of a class lives often <strong>in</strong> acode file which uses the classes name as a prefix and cpp as suffix.So for example if we want to implement a class with the name MyClass we put the declaration code<strong>in</strong>to the file MyClass.h and the implementation code <strong>in</strong>to the file MyClass.cpp. 36.10.2.1 DeclarationA class declaration is <strong>in</strong>troduced by the key word class followed by the class’s name. If a class <strong>in</strong>heritsbase classes, the list of the base classes to <strong>in</strong>herit follows a colon. The declaration code is bracketed <strong>in</strong>tocurled parenthesizes. With the keys public:, protected: and private: the access permissionsare set. Every item (attribute or method) follow<strong>in</strong>g an access permission will get this permission. With<strong>in</strong>the declaration blocks members are declared like variables and methods are declared like functions.3 This concept is rigorously applied <strong>in</strong> the implementation of the Microsoft Foundation Classes MFC.E. Baeck


6.10. OOP WITH CLASSES Page 131The access permissions to an item (attribute or method) are discussed as follows. If it is set to• public,all permissions are assigned, i.e. the item is accessible from outside of the class.• protected,only the class itself and classes, which are derived from this class, are allowed to access.• private,only the class itself is allowed to access the item.The follow<strong>in</strong>g example shows a little class declaration with 2 public attributes and methods and 2 protectedattributes and methods as well. The declaration starts with the classes’ constructor which is declaredwithout return type. The name of the constructor is given by the classes’ name. In general aconstructor can be used with some parameters for special <strong>in</strong>itializations. The declaration of the constructoris followed by the declaration of the destructor. A destructor is declared without a return type. Thename of the destructor is given by the classes’ name with a lead<strong>in</strong>g tilde ˜ character. The class does not<strong>in</strong>herit a base class.List<strong>in</strong>g 6.14: Declar<strong>in</strong>g a Class1 class MyClass: public MyBaseClass2 {3 public:45 MyClass(parameter1, parameter2); // constructor6 ˜MyClass(); // destructor78 <strong>in</strong>t m_nPublicAttribut1;9 <strong>in</strong>t m_nPublicAttribut2;1011 <strong>in</strong>t PublicMethode1();12 <strong>in</strong>t PublicMethode2();1314 protected:15 <strong>in</strong>t m_nProtectedAttribut1;16 <strong>in</strong>t m_nProtectedAttribut2;1718 <strong>in</strong>t ProtectedMethode1();19 <strong>in</strong>t ProtectedMethode2();20 }if an attribute is declared as static, the attribute is an object attribute and not an attribute of the <strong>in</strong>stanceof an object, that means, that this attribute only exists once for an object. A non static attribute will becreated however for each s<strong>in</strong>gle <strong>in</strong>stance of a class.7.8.2013


Page 132 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 136.10.2.2 ImplementationIf a class should be implemented <strong>in</strong> an cpp file, the header file with the class declarations has to be<strong>in</strong>cluded <strong>in</strong> the header section of the cpp file. To avoid multiple <strong>in</strong>clusion of a header file, the header fileshould be protected with a macro #def<strong>in</strong>e discussed <strong>in</strong> section 6.1.The implementation file contents <strong>in</strong> general all implementations of the class’s methods and the implementationof the object attributes, i.e. the attributes with a static property. Every name of a partof a class, which should be implemented starts with the class name followed by the part’s name. Theclass name and the part name are separated by two colons. So an implementation of the above discusseddeclaration could be as follows.List<strong>in</strong>g 6.15: Implement<strong>in</strong>g a Class1 #<strong>in</strong>clude "MyClass.h" // <strong>in</strong>clude the declaration23 // implement the constructor code4 MyClass::MyClass(parameter1, parameter2)5 {6 ... l<strong>in</strong>es of code ...7 }89 // implement the destructor code10 MyClass::˜MyClass()11 {12 ... l<strong>in</strong>es of code ...13 }1415 // implement one of MyClass’s methods16 <strong>in</strong>t MyClass::PublicMethod1()17 {18 ... l<strong>in</strong>es of code ...19 }2021 ...E. Baeck


7Profile ExampleIn this chapter we discuss the implementation of little software project <strong>in</strong> C++ which implements theth<strong>in</strong>-walled approach for some profile types.7.1 Class Concept for the T<strong>in</strong>-Walled ApproachIf we want to build up a class library for model<strong>in</strong>g and describ<strong>in</strong>g a problem, it’s recommended to startwith a general base class, which should content all the common features of our classes.One of this features could be a general logg<strong>in</strong>g code, which should be implemented <strong>in</strong> every class of thelibrary. The logg<strong>in</strong>g code should write <strong>in</strong>formations <strong>in</strong>to a log file. This feature should be available <strong>in</strong>every class of the class library. A second feature is an <strong>in</strong>stance counter. Every <strong>in</strong>stance, which is createdshould be counted by the base class.7.2 ImplementationFigure 7.1 shows the class tree of our profile class library. The common base class Base is <strong>in</strong>herited bya general profile class Profile. The Profile class contents all common features of a profile like <strong>in</strong>our case the model of the th<strong>in</strong>-walled approach with it’s nodes and elements. A special profile, <strong>in</strong> ourexample an U, H or L profile, then is implemented <strong>in</strong> the frame of it’s special class, i.e. UProfile,HProfile or LProfile class.To show the <strong>in</strong>heritance we also <strong>in</strong>herit from the Profile a specialized profile like the UProfileclass. The differences between the UProfile class and the LProfile class for example are obviouslythe <strong>in</strong>put parameters. A second difference between the specialized profiles are the methods to create thegeometry of the profile, i.e. the method to create nodes and elements. If now the geometry of thespecialized profile is created, the general method, to calculate the section values <strong>in</strong> the frame of the TWAis called from each element and from the base class Profile. 1The th<strong>in</strong>-walled profile approach is given by a set of nodes and elements which describes the profile partas l<strong>in</strong>es with a constant thickness. The nodes, described <strong>in</strong> terms of a Node class, and the elements,described <strong>in</strong> terms of a Element class, are created dynamically. The po<strong>in</strong>ter of the nodes and elements1 Base classes are also called superclass or parent class133


Page 134 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Node2..*1Element2..* Base1..*11ProfileUProfile HProfile LProfileFigure 7.1: Class Hierarchy of the Profile Implementationare stored <strong>in</strong> the profile class Profile <strong>in</strong> a po<strong>in</strong>ter array m_pNC and m_pNE.Because the element should be able to calculate it’s section values, we make the element a collection ofit’s nodes. So a direct access to the node’s data is possible. If we would only store the node numbers <strong>in</strong>the element, an element would not be able to calculate it’s section values, because a direct access to thenode’s coord<strong>in</strong>ate values would not be possilble.E. Baeck


7.2. IMPLEMENTATION Page 1357.2.1 Base, the Base Class of all ClassesA UML class diagram <strong>in</strong> figure 7.2 shows the concept of the commonclass Base. The class contents three object attributes, the name ofthe common log file, a pr<strong>in</strong>t buffer and the <strong>in</strong>stance counter. This attributesare declared with an static property. Besides the constructorand the destructor, the class has a method which will write thecontent of the message buffer to the screen and/or <strong>in</strong>to a log file. Theobject method ResetLog deletes an allready exist<strong>in</strong>g log file. Thefollow<strong>in</strong>g code gives the declaration header code of the class Base.Base− m pLogFile[256]: char− m pMsg[256]: char− m nCounter:<strong>in</strong>t+ Base(): −− ˜Base(): −+ AppendLog(..): <strong>in</strong>t+ ResetLog(..): <strong>in</strong>tList<strong>in</strong>g 7.1: Base Class of All ClassesFigure 7.2: TWD’s Base Class1 #ifndef BASE_H_INCLUDED // protect aga<strong>in</strong>st multiple2 #def<strong>in</strong>e BASE_H_INCLUDED // <strong>in</strong>clusion34 // class declaration5 class Base6 {78 public: // can be accessed from everywhere910 // attributes11 // ==========12 // <strong>in</strong>stance counter13 static <strong>in</strong>t m_nCounter; // class attribute1415 // logfile’s name16 static char m_pLogFile[256];// old c str<strong>in</strong>g1718 // str<strong>in</strong>g buffer to log19 static char m_pMsg[256];2021 // methodes22 // ========23 Base(); // constructor to <strong>in</strong>italize24 ˜Base(); // destructor to free memory or to close files ...25 <strong>in</strong>t AppendLog(char* str); // logg<strong>in</strong>g methode26 static void ResetLog(); // reset log27 };28 #endif // BASE_H_INCLUDED7.8.2013


Page 136 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13The implementation code of the class Base is given below. Note, that object attributes must be implementedlike methods. Therefore <strong>in</strong> l<strong>in</strong>e 6 to 8 we implement the object attributes like global variables.List<strong>in</strong>g 7.2: Base Class Implementation1 #<strong>in</strong>clude "base.h" // specify the <strong>in</strong>terface2 #<strong>in</strong>clude // io functions of the c library3 #<strong>in</strong>clude // str<strong>in</strong>g functions of the c library45 // implement class attributes6 <strong>in</strong>t Base::m_nCounter = 0; // counter7 char Base::m_pLogFile[256] = {0};// log file8 char Base::m_pMsg[256] = {0}; // message buffer910 // constructor11 // |class name12 // | | method, the contructor13 Base::Base()14 {15 #ifdef _COMMENT16 // <strong>in</strong>itialization: it is sufficient to set the first item to 017 m_pLogFile[0] = 0; // ... as number18 m_pLogFile[0] = ’\0’; // ... or as character code19 #endif20 // set the default filename21 // |dest<strong>in</strong>ation22 // | |source23 if (!m_pLogFile[0]) strcpy(m_pLogFile,"Base.log");2425 // count the new <strong>in</strong>stance26 m_nCounter++;2728 // create the output str<strong>in</strong>g29 // - pr<strong>in</strong>t <strong>in</strong>to an char array30 spr<strong>in</strong>tf(m_pMsg,"> %d <strong>in</strong>stance(s) created.\n",m_nCounter);3132 // - pr<strong>in</strong>t the message <strong>in</strong>to the file33 AppendLog(m_pMsg);34 }3536 // destructor37 Base::˜Base()38 {39 // create message40 spr<strong>in</strong>tf(m_pMsg,"> Instance %d deleted.\n",m_nCounter);4142 // pr<strong>in</strong>t message43 AppendLog(m_pMsg);4445 // decrement the counter, because an <strong>in</strong>stance is deleted46 m_nCounter--;47 }4849 // AppendLog pr<strong>in</strong>ts a message to the log and to the screen50 <strong>in</strong>t Base::AppendLog(char* pMsg)51 {E. Baeck


7.2. IMPLEMENTATION Page 13752 // pr<strong>in</strong>t to the screen53 pr<strong>in</strong>tf("%s",pMsg);5455 // open the log56 // |file structure (like a channel number57 // |file name58 // | | open mode59 FILE* pHnd = fopen(m_pLogFile,"a");6061 // check the file return62 // (same as if (pHnd == 0)63 if (!pHnd) return 0;6465 // pr<strong>in</strong>t the message66 // | po<strong>in</strong>ter to the file structure FILE67 fpr<strong>in</strong>tf(pHnd,"%s",pMsg);6869 // close the log70 fclose(pHnd);7172 return 1;73 }7475 // ResetLog deletes an allready exist<strong>in</strong>g log-file76 void Base::ResetLog()77 {78 remove(m_pLogFile);79 }7.2.2 Node Class for Model NodesA UML class diagram <strong>in</strong> figure 7.3 shows the concept of the classNode. The class contents the node’s number and a double arrayto hold the <strong>in</strong>stance’s coord<strong>in</strong>ate data. Besides the constructor andthe destructor, the class has a method List which will write the<strong>in</strong>stances data to the log us<strong>in</strong>g the <strong>in</strong>herited method of the classBase::AppendLog. To keep it simple all attributes and methodsof the class are declared as public.In l<strong>in</strong>e 6 we can see, that the class <strong>in</strong>herits it’s base class Base (seesection 7.2.1), therefore we have to <strong>in</strong>clude the Base class header file<strong>in</strong> l<strong>in</strong>e 4.Node+ m nNo: <strong>in</strong>t+ m dx[2]: double+ Node(..): −− ˜Node(): −+ List(..): voidFigure 7.3: The Class NodeList<strong>in</strong>g 7.3: Node Class’s Header1 #ifndef NODE_H_INCLUDED2 #def<strong>in</strong>e NODE_H_INCLUDED34 #<strong>in</strong>clude "Base.h" // <strong>in</strong>clude Base class’s header5 // | <strong>in</strong>herit from Base6 class Node: public Base7 {87.8.2013


Page 138 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13109 public:11 // attribute12 <strong>in</strong>t m_nNo; // node number13 double m_dx[2]; // x,y values (vector)1415 public:16 // constructor: x,y optional17 Node(<strong>in</strong>t nNo, double x = 0., double y = 0.);1819 // destructor20 ˜Node();2122 // list the node’s data23 void List();24 };25 #endif // NODE_H_INCLUDEDThe implementation code of the class Node is given below. Note, that constructor is used with it’sparameters to <strong>in</strong>itialize the node coord<strong>in</strong>ates. If coord<strong>in</strong>ate values are passed by the constructor, thevalues are assigned to the attributes. The constructor at the end will pr<strong>in</strong>t the nodes data <strong>in</strong>to the log file.List<strong>in</strong>g 7.4: Node Class’s Implementation1 #<strong>in</strong>clude "node.h"2 #<strong>in</strong>clude 34 // constructor5 // parameters call Base class6 Node::Node(<strong>in</strong>t nNo, double x, double y) : Base()7 {8 // assign the coord<strong>in</strong>ates9 m_nNo = nNo;10 m_dx[0] = x;11 m_dx[1] = y;1213 // pr<strong>in</strong>t the data14 List();15 }1617 // destructor (noth<strong>in</strong>g to do)18 Node::˜Node() { }1920 // List method, pr<strong>in</strong>ts Node’s data21 void Node::List()22 {23 spr<strong>in</strong>tf(m_pMsg,24 "> node: no = %2d, x = %10.3f y = %10.3f\n",25 m_nNo,m_dx[0],m_dx[1]);26 AppendLog(m_pMsg);27 }E. Baeck


7.2. IMPLEMENTATION Page 1397.2.3 Check<strong>in</strong>g the Node ClassTo check the node class, we implement a little test<strong>in</strong>g frame, which simple creates some Node <strong>in</strong>stances,assign some data, pr<strong>in</strong>t the Node data us<strong>in</strong>g it’s List method and delet<strong>in</strong>g the Node <strong>in</strong>stance at theend. Because we <strong>in</strong>herit the Base class features, the creation and the deletion of an <strong>in</strong>stance is loggedto the screen, so we can simple check this event.The test<strong>in</strong>g code is given with<strong>in</strong> the follow<strong>in</strong>g ma<strong>in</strong> steps.• If we want to use the Node class, we have to declare it with the <strong>in</strong>clusion of it’s declaration header,this is done <strong>in</strong> the first l<strong>in</strong>e.• A simple Node <strong>in</strong>stance is created by declar<strong>in</strong>g a variable N1 of the type Node.• To <strong>in</strong>itialize with special parameters we assign the return of the constructor to a variable of typeNode, called N2.• Then we pr<strong>in</strong>t the data of the created nodes N1 and N2 by call<strong>in</strong>g their method List. This is doneus<strong>in</strong>g the dot access (.).• After this we declare an address po<strong>in</strong>ter pN3 2 of the to a Node <strong>in</strong>stance us<strong>in</strong>g the Node* type.Because there is no valid <strong>in</strong>stance address <strong>in</strong> N3 we <strong>in</strong>itialize it with a zero value. 3• To assign a valid address of a Node <strong>in</strong>stance to pN3, we create a Node <strong>in</strong>stance dynamicallyby the usage of the new operator. The return of the new Node is an address and this address isassigned to our third Node* variable N3.• To pr<strong>in</strong>t the data of the third node we have to use the arrow access because it’s a po<strong>in</strong>ter variable(->).• After the pr<strong>in</strong>t<strong>in</strong>g of the content of the third Node <strong>in</strong>stance we remove the <strong>in</strong>stance from memoryus<strong>in</strong>g the delete operator. To avoid the access to an <strong>in</strong>valid address, we check the address po<strong>in</strong>teraga<strong>in</strong>st zero.The code of the test<strong>in</strong>g frame is given below.List<strong>in</strong>g 7.5: Checkenvironment for the Node Class1 #<strong>in</strong>clude "Node.h" // load Node header2 #<strong>in</strong>clude // used for pr<strong>in</strong>tf34 <strong>in</strong>t ma<strong>in</strong>() // the ma<strong>in</strong> rout<strong>in</strong>e5 {6 Node N1 = Node(1); // standard coord<strong>in</strong>ates used7 Node N2 = Node(2,1.1,1.2); // use parameters to <strong>in</strong>itialize89 N1.List(); // list the data of node 110 N2.List(); // list the data of node 21112 // creat<strong>in</strong>g 3rd Node <strong>in</strong>stances dynamically2 A prefix <strong>in</strong> the variable name of p shows, that it’s a po<strong>in</strong>ter variable, which means, that the variable contents the address ofthe assigned data and not the data itself.3 A zero address value means, that no memory is referenced to this address po<strong>in</strong>ter.7.8.2013


Page 140 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1313 Node* pN3 = 0; // address of a Node <strong>in</strong>stance14 // 0: no memory assigned1516 // create an <strong>in</strong>stance dynamically with the new operator17 pr<strong>in</strong>tf("now create the <strong>in</strong>stance for pN3\n");18 pN3 = new Node(3,2.1,2.2);1920 // list data of node 3. note, we use the ’->’ operator21 // if the variable contents an adress an not the data itself22 pN3->List();2324 // delete the Node <strong>in</strong>stance us<strong>in</strong>g the delete operator25 if (pN3) delete pN3;26 }The Output of the above discussed codeis given <strong>in</strong> figure 7.4. If an <strong>in</strong>stance iscreated, we see <strong>in</strong> the log the messageof the Base class constructor, whichcounts the <strong>in</strong>stances. This output isfollowed by the output of the Nodeclass constructor, which pr<strong>in</strong>ts the coord<strong>in</strong>atesof the Node <strong>in</strong>stance. Herewe can see, that the first node will getthe standard zero values and the second<strong>in</strong>stance will get the coord<strong>in</strong>ates, whichare passed to the constructor.Figure 7.4: Output of the Node Check ProgramThen the created <strong>in</strong>stances’ data are pr<strong>in</strong>ted us<strong>in</strong>g their List methods. Then we create the third <strong>in</strong>stanceand their data are pr<strong>in</strong>ted like <strong>in</strong> the previous cases. After that the third Node <strong>in</strong>stance is deleted explicitlyand we see that the <strong>in</strong>stance counter <strong>in</strong> the Base class destructor is decremented. Clos<strong>in</strong>g the programthe destructor of the Base class of the statically created <strong>in</strong>stances N1 and N2 is automatically executed.So we can see the decrementation of the <strong>in</strong>stance counter down to zero.E. Baeck


7.2. IMPLEMENTATION Page 1417.2.4 Element Class for Model ElementsA UML class diagram <strong>in</strong> figure 7.5 shows the concept of the classElement. The Element class get’s the po<strong>in</strong>ter of it’s Node <strong>in</strong>stances.If this po<strong>in</strong>ters (the addresses of the Node <strong>in</strong>stances) areknown, the Element will be able to calculate all it’s sections values.So we can encapsulate this features <strong>in</strong>to the Element. At the end toget the profiles total section values we simply have to add up all it’sElement’s values.To get a general implementation, we <strong>in</strong>troduce a simple conta<strong>in</strong>er forthe Node <strong>in</strong>stance po<strong>in</strong>ters, which is a simple C array. In the generalcase we can have elements with an arbitrary number of nodes, so we<strong>in</strong>troduce the number of Node po<strong>in</strong>ters m_nNoX, which <strong>in</strong> our casewill be 2. The Node <strong>in</strong>stance po<strong>in</strong>ters will be stored <strong>in</strong> the arraym_pN, which we have to allocate dynamically.Besides the Node <strong>in</strong>stance po<strong>in</strong>ters, our element need to know it’sthickness. The thickness is stored <strong>in</strong> the attribute m_dt.The follow<strong>in</strong>g attributes will hold the element’s section values.Element+ m nNoX : <strong>in</strong>t+ m nNo : <strong>in</strong>t+ m dt : double+ m pN : Node**+ m dL : double+ m dA : double+ m dS[2] : double+ m dI[3] : double+ Element(..) : −− ˜Element(): −+ List() : void+ InitResults() : void+ SetData() : <strong>in</strong>tFigure 7.5: The Class Element• m_dL, the length of the element. This value is used to calculate the section values.• m_dA, the area of the element (see section C.1.1).• m_dS, the static moments of the element, [0]: S y , [1]: S z (see section C.1.2).• m_dI, the moments of <strong>in</strong>ertia of the element, [0]: I yy , [1]: I zz , [2]: I yz , (see section C.1.3).Besides the constructor and the destructor, the class provides a method which will write the <strong>in</strong>stances datato the log us<strong>in</strong>g the <strong>in</strong>herited method of the class Base::AppendLog. The method InitResultswill <strong>in</strong>itialize all <strong>in</strong>ternal and public items of the element, which are used to get and hold the result values.The method SetData will calculate the elements section values.The Element class provides only one constructor, i.e only one <strong>in</strong>terface. The constructor comes withfour parameters which will describe a l<strong>in</strong>ear element. 4• <strong>in</strong>t nNo, the element’s number.• Node* pN1, the <strong>in</strong>stance po<strong>in</strong>ter to the element’s start<strong>in</strong>g node.• Node* pN2, the <strong>in</strong>stance po<strong>in</strong>ter to the element’s term<strong>in</strong>at<strong>in</strong>g node.• double dt, the element’s thickness.We have to note, that all element’s methods suppose, that the <strong>in</strong>put data are correct. Error check<strong>in</strong>g willbe performed later, if we create an general TWA profile.4 Introduc<strong>in</strong>g further <strong>in</strong>terfaces, the library can be extended by other element types.7.8.2013


Page 142 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13As we have seen <strong>in</strong> figure 7.5 the Element class may be considered as composition of Node <strong>in</strong>stances.One element will have 2 nodes or more.ElementNode1 2..*Figure 7.6: UML-Diagram of the Element CompositionList<strong>in</strong>g 7.6: Element Class’s Header1 #ifndef ELEMENT_H_INCLUDED2 #def<strong>in</strong>e ELEMENT_H_INCLUDED34 #<strong>in</strong>clude "Base.h" // <strong>in</strong>clude Base-Class’s header5 class Node; // we need a Node po<strong>in</strong>ter6107 class Element: public Base8 {9 public:11 // attributes12 <strong>in</strong>t m_nNoX; // number of Nodes13 <strong>in</strong>t m_nNo; // element number14 double m_dt; // thickness15 // adress of the Node <strong>in</strong>stances po<strong>in</strong>ter array (therefore 2 *)16 Node** m_pN;1718 // section attributes19 double m_dL; // element length20 double m_dA; // element area21 double m_dS[2]; // element’s static moments22 double m_dI[3]; // element’s moments of <strong>in</strong>ertia2324 // methods25 // constructor: only with all element data26 Element(<strong>in</strong>t nNo,Node* pN1, Node* pN2, double dt);2728 // destructor29 ˜Element();3031 // list the data32 void List();3334 // <strong>in</strong>itialize the results35 void InitResults();3637 // calculate results38 <strong>in</strong>t SetData();39 };40 #endif // ELEMENT_H_INCLUDEDThe implementation code of the class Element is given below. Note, that constructor is used with it’sparameters to <strong>in</strong>itialize the element data.E. Baeck


7.2. IMPLEMENTATION Page 143List<strong>in</strong>g 7.7: Element Class’s Implementation1 #<strong>in</strong>clude "element.h" // declare the element class2 #<strong>in</strong>clude // for pr<strong>in</strong>t<strong>in</strong>g3 #<strong>in</strong>clude // used for memory access (memset)4 #<strong>in</strong>clude // to calculate the root56 #<strong>in</strong>clude "node.h" // we should know the Node too78 // constructor9 Element::Element(<strong>in</strong>t nNo, Node* pN1, Node* pN2, double dt)10 {11 m_nNoX = 2; // we only have elements with two Nodes1213 // assign<strong>in</strong>g attributes14 m_nNo = nNo;15 m_dt = dt;1617 // Node address array18 // !!! we have allocate it !!!19 m_pN = new Node*[m_nNoX];2021 // assign the Node po<strong>in</strong>ters22 m_pN[0] = pN1;23 m_pN[1] = pN2;2425 // <strong>in</strong>itialize the result attributs26 InitResults();2728 pr<strong>in</strong>tf("> element %d created.\n",m_nNo);29 }3031 // destructor: note: the Node <strong>in</strong>stances have to be freed outside32 Element::˜Element()33 {34 pr<strong>in</strong>tf("> element %d deleted.\n",m_nNo);35 }3637 // <strong>in</strong>itialize the result attributs38 void Element::InitResults()39 {40 m_dL = 0.;41 m_dA = 0.;4243 // <strong>in</strong>itialize an array44 // | dest<strong>in</strong>ation (array’s address)45 // | | byte to copy46 // | | | number of byte to copy47 memset((void*)&m_dS[0],0,2*sizeof(double)); // m_dS == &m_dS[0]48 memset((void*)&m_dI[0],0,3*sizeof(double));49 }5051 // list the elements data52 void Element::List()53 {54 // pr<strong>in</strong>t header7.8.2013


Page 144 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1355 spr<strong>in</strong>tf(m_pMsg,"element %2d, t = %10.2f\n",m_nNo,m_dt);56 AppendLog(m_pMsg);5758 // pr<strong>in</strong>t element’s Node data59 for (<strong>in</strong>t i=0;iList();62 }6364 // list result values65 spr<strong>in</strong>tf(m_pMsg," L..........: %12.3f mm\n",m_dL);66 AppendLog(m_pMsg);67 spr<strong>in</strong>tf(m_pMsg," A..........: %12.3f cmˆ2\n",m_dA/1.e2);68 AppendLog(m_pMsg);69 spr<strong>in</strong>tf(m_pMsg," Sx.........: %12.3e cmˆ3\n",m_dS[0]/1.e3);70 AppendLog(m_pMsg);71 spr<strong>in</strong>tf(m_pMsg," Sy.........: %12.3e cmˆ3\n",m_dS[1]/1.e3);72 AppendLog(m_pMsg);73 spr<strong>in</strong>tf(m_pMsg," Ixx........: %12.3e cmˆ4\n",m_dI[0]/1.e4);74 AppendLog(m_pMsg);75 spr<strong>in</strong>tf(m_pMsg," Iyy........: %12.3e cmˆ4\n",m_dI[1]/1.e4);76 AppendLog(m_pMsg);77 spr<strong>in</strong>tf(m_pMsg," Ixy........: %12.3e cmˆ4\n",m_dI[2]/1.e4);78 AppendLog(m_pMsg);79 }8081 // calculate all supported the section values of an element82 <strong>in</strong>t Element::SetData()83 {84 // <strong>in</strong>troduce some helper variables85 double dxc[2]; // element center coord<strong>in</strong>ates86 double dLp[2]; // projected length of the element8788 // ... and calculate them89 for (<strong>in</strong>t i=0;im_dx[i] + m_pN[0]->m_dx[i])/2.;9394 // projected length95 dLp[i] = m_pN[1]->m_dx[i] - m_pN[0]->m_dx[i];96 }9798 // calculate the length of the element99 m_dL = sqrt(dLp[0]*dLp[0] + dLp[1]*dLp[1]);100101 // calculate the area102 m_dA = m_dL * m_dt;103104 // calculate the static moment105 for (<strong>in</strong>t i=0;i


7.2. IMPLEMENTATION Page 145111 // Ixx, Iyy112 <strong>in</strong>t j;113 for (<strong>in</strong>t i=0;i ok!123 }7.2.5 Check<strong>in</strong>g the Element ClassTo check the element class, we implement a little test<strong>in</strong>g frame, which simple creates an element tocalculate the section values of a flat steel Fl200x4. The orig<strong>in</strong> of the used coord<strong>in</strong>ate system is <strong>in</strong> thecenter of the element. The element is orientated <strong>in</strong>to the vertical direction, i.e. <strong>in</strong> the direction of thesecond coord<strong>in</strong>ate.The program executes the follow<strong>in</strong>g steps.• Allocate the Node <strong>in</strong>stances.We create 2 node 1 at the position (0, −100) and node 2 at (0, 100).• Allocate the Element <strong>in</strong>stances.Element 1 gets the Node <strong>in</strong>stance po<strong>in</strong>ter 1 and 2 and the element’s thickness.• Calculate the section values.• List the element’s data.• Delete all created <strong>in</strong>stances.The code of the test<strong>in</strong>g frame is given below.List<strong>in</strong>g 7.8: Check Environment for the Node Class1 #<strong>in</strong>clude 2 #<strong>in</strong>clude "node.h" // what is a Node3 #<strong>in</strong>clude "element.h" // what is an Element45 <strong>in</strong>t ma<strong>in</strong>()6 {7 // create a flat steel Fl 200x48 // we need 2 Nodes for one Element9 // the are allocated at the heap10 // No x y11 Node* pN1 = new Node(1, 0., -100.);12 Node* pN2 = new Node(2, 0., 100.);1314 // create one Element on the heap15 Element* pE1 = new Element(1,pN1,pN2,4.);7.8.2013


Page 146 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 131617 // calculate the values18 pE1->SetData();1920 // list element’s data21 pE1->List();2223 // clear the memory24 delete pN1;25 delete pN2;26 delete pE1;27 return 0;28 }The Output of the above discussed codeis given <strong>in</strong> figure 7.4. If an <strong>in</strong>stance iscreated, we see <strong>in</strong> the log the messageof the Base class constructor, whichcounts the <strong>in</strong>stances.This output isfollowed by the output of the Nodeclass constructor, which pr<strong>in</strong>ts the coord<strong>in</strong>atesof the Node <strong>in</strong>stance.The constructor of the elementshows us the element’s number.After this the Element <strong>in</strong>stance is created.Afterthe calculation of the section valuesis done, the element’s List method isFigure 7.7: Output of the Element Check Programcalled, i.e. we see the element’s number and it’s thickness. Then all node data of this element are listedand at the end we see the calculated section values.Because the element is vertical we only get an area ofA = L · t = 200 · 4 mm 2 = 8cm 2and a moment of <strong>in</strong>ertia ofI xx = 1 12 · L3 · t = 112 · 2003 · 4 mm 2 = 266, 7cm 4E. Baeck


7.2. IMPLEMENTATION Page 1477.2.6 Profile Class for Model ProfilesA UML class diagram <strong>in</strong> figure 7.8 shows the concept of the classProfile. The class contents the profile’s name and a conta<strong>in</strong>er forthe profile’s nodes and profile’s elements. The conta<strong>in</strong>ers are build bya simple dynamical array and an <strong>in</strong>teger, which holds the length ofthe array.The methods of the class creates the conta<strong>in</strong>ers with a specifiedlength. A Node <strong>in</strong>stance and an Element <strong>in</strong>stance can be addedby an specific Add function. To check the node and element <strong>in</strong>formationCheck methods are implemented, which checks the existentsof the referenced node and element number. Besides the constructorand the destructor, the class has a method which will writethe <strong>in</strong>stances data to the log us<strong>in</strong>g the <strong>in</strong>herited method of the classBase::AppendLog. To keep it simple all attributes and methodsare set to public.We have the follow<strong>in</strong>g class attributes. The mean<strong>in</strong>g of the sectionvalues is discussed <strong>in</strong> section C.1.• m_pName[256], the profile’s name• m_dA, total area• m_dS[2], total static moment’s• m_de[2], center of mass coord<strong>in</strong>ates• m_dIu[3], moment of <strong>in</strong>ertia <strong>in</strong> user coord<strong>in</strong>ates• m_dIc[3], moment of <strong>in</strong>ertia <strong>in</strong> center of mass coord<strong>in</strong>ates• m_dIm[2], moment of <strong>in</strong>ertia <strong>in</strong> ma<strong>in</strong> coord<strong>in</strong>ates• m_dAlpha, ma<strong>in</strong> axis angle• m_pNC, po<strong>in</strong>ter to Node <strong>in</strong>stance array• m_nNC, length of node conta<strong>in</strong>erProfile+ m pName[256] : char+ m dA : double+ m dS[2] : double+ m de[2] : double+ m dIu[3] : double+ m dIc[3] : double+ m dIm[2] : double+ m dAlpha : double+ m pNC : Node**+ m nNC : <strong>in</strong>t+ m pEC : Element**+ m nEC : <strong>in</strong>t+ Profile(..) : −− ˜Profile(): −+ AddNodeConta<strong>in</strong>er(..) : <strong>in</strong>t+ AddElementConta<strong>in</strong>er(..) : <strong>in</strong>t+ AddNode(Node* pN) : <strong>in</strong>t+ AddElement(..) : <strong>in</strong>t+ List() : void+ DeleteNodes() : <strong>in</strong>t+ DeleteElements() : <strong>in</strong>t+ CheckNode(..) : <strong>in</strong>t+ CheckElement(..) : <strong>in</strong>t+ ResetSectionValues() : void+ GetSectionValues() : <strong>in</strong>t+ ListSectionValues() : void+ MTrans() : doubleFigure 7.8: The Class Profile• m_pEC, po<strong>in</strong>ter to Element <strong>in</strong>stance array• m_nEC, length of element conta<strong>in</strong>er7.8.2013


Page 148 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13The profile class has the follow<strong>in</strong>g methods.methode parameter type commentProfileconstructorcNameconst char profile’s name˜ProfileAddNodeConta<strong>in</strong>erdestructorcreate the node conta<strong>in</strong>ernLength <strong>in</strong>tlength of the arrayAddElementConta<strong>in</strong>ercreate the element conta<strong>in</strong>ernLength <strong>in</strong>tlength of the arrayAddNodeadds a Node po<strong>in</strong>ter <strong>in</strong>to it’s array slot,error check<strong>in</strong>g is donepN Node* <strong>in</strong>stance po<strong>in</strong>ter to storeAddElementadds an Element po<strong>in</strong>ter <strong>in</strong>to it’s arrayslot, error check<strong>in</strong>g is donepE Element* <strong>in</strong>stance po<strong>in</strong>ter to storeListDeleteNodesDeleteElementsCheckNodepr<strong>in</strong>ts all data of the profiledeletes all nodes and their conta<strong>in</strong>erdeletes all elements and their conta<strong>in</strong>ercheck the data of a nodepN Node* Node <strong>in</strong>stance to checkCheckElementcheck the data of an elementpE Element* Element <strong>in</strong>stance to checkResetSectionValuesGetSectionValuesMTrans<strong>in</strong>itialize all section valuespr<strong>in</strong>t the section valuescalculate the ma<strong>in</strong> values of the momentof <strong>in</strong>ertia and the rotation angleIn this version of the implementation the <strong>in</strong>put data is checked only by the Profile class, because <strong>in</strong> thiscontext it does not sence to access nodes and elements directly. So all <strong>in</strong>put data runs through the profile’s<strong>in</strong>put functions.If errors are detected we give up runn<strong>in</strong>g backward us<strong>in</strong>g error codes. If an item is checked and an erroris detected an exception is thrown. So the apply<strong>in</strong>g rout<strong>in</strong>e has to catch the exception us<strong>in</strong>g the code ofthe profile with<strong>in</strong> a try block..E. Baeck


7.2. IMPLEMENTATION Page 149The declaration of the class Profile is given by the follow<strong>in</strong>g list<strong>in</strong>g.List<strong>in</strong>g 7.9: Profile Class’s Header1 #ifndef PROFILE_H_INCLUDED2 #def<strong>in</strong>e PROFILE_H_INCLUDED34 #<strong>in</strong>clude "Base.h" // we should know someth<strong>in</strong>g about the Base5 class Node; // we use Node po<strong>in</strong>ters6 class Element; // we use Element po<strong>in</strong>ters78 // a profile’s class9 class Profile: public Base10 {11 public:1213 // <strong>in</strong>terface - constructor14 Profile(const char* cName);1516 // destructor17 ˜Profile();1819 // create a Node conta<strong>in</strong>er20 <strong>in</strong>t AddNodeConta<strong>in</strong>er(<strong>in</strong>t nLength);2122 // create a Element conta<strong>in</strong>er23 <strong>in</strong>t AddElementConta<strong>in</strong>er(<strong>in</strong>t nLength);2425 // add a Node26 <strong>in</strong>t AddNode(Node* pN);2728 // add a Element29 <strong>in</strong>t AddElement(Element* pE);3031 // list all values32 void List();3334 // delete/clear all Nodes35 <strong>in</strong>t DeleteNodes();3637 // delete/clear all Nodes38 <strong>in</strong>t DeleteElements();3940 // check the Node <strong>in</strong>stance41 <strong>in</strong>t CheckNode(Node* pN);4243 // check the Element <strong>in</strong>stance44 <strong>in</strong>t CheckElement(Element* pE);4546 // methods to calculate the section values47 // - reset48 void ResetSectionValues();4950 // - calculate the section values51 <strong>in</strong>t GetSectionValues();527.8.2013


Page 150 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1353 // - list them54 void ListSectionValues();5556 // - ma<strong>in</strong> axis transformation57 double MTrans();5859 // -----------------------60 // attributes of the class61 // - profile’s name62 char m_pName[256];6364 // - section values65 double m_dA; // area66 double m_dS[2]; // static moment67 double m_de[2]; // center of mass coord<strong>in</strong>ates68 double m_dIu[3]; // M o I <strong>in</strong> user coord<strong>in</strong>ates69 double m_dIc[3]; // M o I <strong>in</strong> ma<strong>in</strong> CS70 double m_dIm[2]; // M o I ma<strong>in</strong> values71 double m_dAlpha; // rotation angle7273 // Node conta<strong>in</strong>er74 Node** m_pNC; // Node <strong>in</strong>stance array75 <strong>in</strong>t m_nNC; // array’s dimension7677 // Element conta<strong>in</strong>er78 Element** m_pEC; // Element <strong>in</strong>stance array79 <strong>in</strong>t m_nEC; // array’s dimension80 };81 #endif // PROFILE_H_INCLUDEDThe implementation code of the class Profile is given below. Note, that constructor is used with it’sparameters to <strong>in</strong>itialize the Profile data.List<strong>in</strong>g 7.10: Profile Class’s Implementation1 /*2 Implementation of the Profile class3 */4 #<strong>in</strong>clude "profile.h"5 #<strong>in</strong>clude "node.h"6 #<strong>in</strong>clude "element.h"78 #<strong>in</strong>clude // standard io (pr<strong>in</strong>t<strong>in</strong>g)9 #<strong>in</strong>clude // to use str<strong>in</strong>g functions10 #<strong>in</strong>clude // to use math functions1112 // constructor13 Profile::Profile(const char* pName): Base()14 {15 // copy name16 // dest. source17 strcpy(m_pName,pName);1819 // <strong>in</strong>itialize the conta<strong>in</strong>er20 m_pNC = 0; // for Nodes21 m_nNC = 0;E. Baeck


7.2. IMPLEMENTATION Page 15122 m_pEC = 0; // for Elements23 m_nEC = 0;2425 // reset the results26 ResetSectionValues();27 }2829 // destructor30 Profile::˜Profile()31 {32 // first delete the content33 DeleteNodes();34 DeleteElements();3536 // delete the conta<strong>in</strong>ers37 if (m_pNC) delete [] m_pNC; // for Nodes38 if (m_pEC) delete [] m_pEC; // for Elements39 }4041 // reset the section values42 void Profile::ResetSectionValues()43 {44 m_dA = 0.;45 // dest<strong>in</strong>ation po<strong>in</strong>ter46 // | | byte to copy47 // | | | number of bytes to copy48 memset((void*)m_dS, 0, sizeof(double)*2);49 memset((void*)m_de, 0, sizeof(double)*2);50 memset((void*)m_dIu, 0, sizeof(double)*3);51 memset((void*)m_dIc, 0, sizeof(double)*3);52 memset((void*)m_dIm, 0, sizeof(double)*2);53 m_dAlpha = 0.;54 }5556 // delete all Nodes57 <strong>in</strong>t Profile::DeleteNodes()58 {59 // check the conta<strong>in</strong>er60 if (!m_pNC) return 0;6162 // delete the Node <strong>in</strong>stances63 for (<strong>in</strong>t i=0;i


Page 152 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1378 {79 // check the conta<strong>in</strong>er80 if (!m_pEC) return 0;8182 // delete the Node <strong>in</strong>stances83 for (<strong>in</strong>t i=0;i


7.2. IMPLEMENTATION Page 153134 AppendLog(m_pMsg);135 AppendLog((char*)"Moment of Inertia <strong>in</strong> user cooord<strong>in</strong>ates:\n");136 spr<strong>in</strong>tf(m_pMsg," I_yy.....................: %10.2f cmˆ4\n",m_dIu[0]/1.e4);137 AppendLog(m_pMsg);138 spr<strong>in</strong>tf(m_pMsg," I_zz.....................: %10.2f cmˆ4\n",m_dIu[1]/1.e4);139 AppendLog(m_pMsg);140 spr<strong>in</strong>tf(m_pMsg," I_yz.....................: %10.2f cmˆ4\n",m_dIu[2]/1.e4);141 AppendLog(m_pMsg);142 AppendLog((char*)"Moment of Inertia <strong>in</strong> centroid cooord<strong>in</strong>ates:\n");143 spr<strong>in</strong>tf(m_pMsg," I_yy.....................: %10.2f cmˆ4\n",m_dIc[0]/1.e4);144 AppendLog(m_pMsg);145 spr<strong>in</strong>tf(m_pMsg," I_zz.....................: %10.2f cmˆ4\n",m_dIc[1]/1.e4);146 AppendLog(m_pMsg);147 spr<strong>in</strong>tf(m_pMsg," I_yz.....................: %10.2f cmˆ4\n",m_dIc[2]/1.e4);148 AppendLog(m_pMsg);149 AppendLog((char*)"Moment of Inertia <strong>in</strong> ma<strong>in</strong> cooord<strong>in</strong>ates:\n");150 spr<strong>in</strong>tf(m_pMsg," I_eta....................: %10.2f cmˆ4\n",m_dIm[0]/1.e4);151 AppendLog(m_pMsg);152 spr<strong>in</strong>tf(m_pMsg," I_zeta...................: %10.2f cmˆ4\n",m_dIm[1]/1.e4);153 AppendLog(m_pMsg);154 spr<strong>in</strong>tf(m_pMsg," alpha....................: %10.2f  ◦ \n",m_dAlpha*45./atan(1.));155 AppendLog(m_pMsg);156 }157158 // allocate the Node space159 <strong>in</strong>t Profile::AddNodeConta<strong>in</strong>er(<strong>in</strong>t nLength)160 {161 // delete the old conta<strong>in</strong>er162 DeleteNodes();163164 // create the Node array165 m_pNC = new Node* [nLength];166 if (!m_pNC) return 0; // no memory available167168 // <strong>in</strong>itialize the memory with Null (0)169 // dest<strong>in</strong>ation address170 // | | byte to copy171 memset((void*)m_pNC,0,sizeof(Node*)*nLength);172173 // save the length174 m_nNC = nLength;175176 return nLength;177 }178179 // allocate the Element space180 <strong>in</strong>t Profile::AddElementConta<strong>in</strong>er(<strong>in</strong>t nLength)181 {182 // delete the old conta<strong>in</strong>er183 DeleteElements();184185 // create the Element array186 m_pEC = new Element* [nLength];187 if (!m_pEC) return 0; // no memory available188189 // <strong>in</strong>itialize the memory with Null (0)7.8.2013


Page 154 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13190 // dest<strong>in</strong>ation address191 // | | byte to copy192 memset((void*)m_pEC,0,sizeof(Element*)*nLength);193194 // save the length195 m_nEC = nLength;196197 return nLength;198 }199200 // Add an element and it’s Nodes201 <strong>in</strong>t Profile::AddElement(Element* pE)202 {203 // conta<strong>in</strong>er available204 if (!m_pEC) throw "*** Error: no element conta<strong>in</strong>er!\n";205206 // check element address207 if (!pE) throw "*** Error: no element po<strong>in</strong>ter\n";208209 // check the <strong>in</strong>stance and throw an exception,210 // if there is an error211 CheckElement(pE);212213 // add the element214 m_pEC[pE->m_nNo -1] = pE;215216 // add the element’s Nodes217 m_pNC[pE->m_pN[0]->m_nNo -1] = pE->m_pN[0];218 m_pNC[pE->m_pN[1]->m_nNo -1] = pE->m_pN[1];219220 return 1;221 }222223 // check an element <strong>in</strong>stance224 <strong>in</strong>t Profile::CheckElement(Element* pE)225 {226 // check <strong>in</strong>stance po<strong>in</strong>ter227 if (!pE) throw "*** Error: <strong>in</strong>valid element po<strong>in</strong>ter!";228229 if (pE->m_nNo < 1 || pE->m_nNo > m_nEC)230 throw "*** Error: <strong>in</strong>valid element number!";231232 // check the Node <strong>in</strong>stances233 for (<strong>in</strong>t i=0;im_pN[i];236 if (!pN)237 throw "*** Error: Node <strong>in</strong>stance not found!";238 if (pN->m_nNo < 1 || pN->m_nNo > m_nNC)239 throw "*** Error: Node number <strong>in</strong>valid!";240 }241242 // check Node numbers243 if (pE->m_pN[0]->m_nNo == pE->m_pN[1]->m_nNo)244 throw "*** Error: Invalid Node numbers";245E. Baeck


7.2. IMPLEMENTATION Page 155246 return 0;247 }248249 // calculate the section values250 <strong>in</strong>t Profile::GetSectionValues()251 {252 // <strong>in</strong>itialization253 ResetSectionValues();254255 // sum over all elements256 for (<strong>in</strong>t i=0;iSetData();266267 // sum up the values268 m_dA += pE->m_dA;269 for (<strong>in</strong>t j=0;jm_dS[j];270 for (<strong>in</strong>t j=0;jm_dI[j];271 }272273 // calculate the center of mass274 m_de[0] = m_dS[1]/m_dA;275 m_de[1] = m_dS[0]/m_dA;276277 // calculate the ma<strong>in</strong> values278 MTrans();279280 return 1;281 }282283 // ma<strong>in</strong> axis transformation284 // return: angle285 double Profile::MTrans()286 {287 // M o I <strong>in</strong> CCS (center of mass)288 m_dIc[0] = m_dIu[0] - m_de[1]*m_de[1]*m_dA;289 m_dIc[1] = m_dIu[1] - m_de[0]*m_de[0]*m_dA;290 m_dIc[2] = m_dIu[2] - m_de[0]*m_de[1]*m_dA;291292 // helper values293 double dIdel = m_dIc[0] - m_dIc[1];294 double dIsum = m_dIc[0] + m_dIc[1];295 double dIsqr = sqrt(dIdel*dIdel +4.*m_dIc[2]*m_dIc[2]);296297 // M o I <strong>in</strong> ma<strong>in</strong> coord<strong>in</strong>ate system298 m_dIm[0] = 0.5*(dIsum + dIsqr);299 m_dIm[1] = 0.5*(dIsum - dIsqr);300301 // calcualate the rotation angle7.8.2013


Page 156 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13302 m_dAlpha = 0.5*atan2(2.*m_dIc[2],dIdel);303304 return m_dAlpha;305 }7.2.7 Check<strong>in</strong>g the Profile ClassTo check the profile class, we implement a little test<strong>in</strong>g frame, which simple creates an profile to calculatethe section values of a flat steel Fl200x4. The orig<strong>in</strong> of the used coord<strong>in</strong>ate system is <strong>in</strong> one endpo<strong>in</strong>t andthe profile is rotated by 45 ◦ . We have used this example already to check the element <strong>in</strong> section 7.2.5.The program executes the follow<strong>in</strong>g steps.• Allocate the Profile <strong>in</strong>stances.We pass the name of the profile.• Allocate the conta<strong>in</strong>ers.We need a node space of two and an element space of one.• Create the Node <strong>in</strong>stances.To check it flexible we use macros to enable or disable this part of code. Because <strong>in</strong> our case thereis no macro def<strong>in</strong>ition, we get the code with<strong>in</strong> the #else branch.• Create the Element <strong>in</strong>stance.We pass the element number, the Node <strong>in</strong>stance po<strong>in</strong>ters and the element’s thickness.• Add the element to the profile.Add<strong>in</strong>g the element to the profile, the element’s data are checked, so if there will be detected anerror, the rout<strong>in</strong>e will be canceled by an exception, we have to handle.• Calculate the section values and• list the profiles data.• At the end we should not forget to clear the memory, delet<strong>in</strong>g the Profile <strong>in</strong>stance.All the above discussed steps should be done with<strong>in</strong> a try block, so that we can handle detected errors<strong>in</strong> the follow<strong>in</strong>g catch blocks.• The first catch block will handle our exceptions, because we pass a const char* to theexception throw<strong>in</strong>g them.• The second catch block will handle all other exceptions. So, if we divide by zero or if we haveforgotten to check one case, the program is not crash<strong>in</strong>g, an unspecified exception is thrown.E. Baeck


7.2. IMPLEMENTATION Page 157The code of the test<strong>in</strong>g frame is given below.List<strong>in</strong>g 7.11: Check Environment for the Profile Class1 #<strong>in</strong>clude 2 #<strong>in</strong>clude 3 #<strong>in</strong>clude "profile.h" // we start with the profile4 #<strong>in</strong>clude "node.h" // and will need some nodes5 #<strong>in</strong>clude "element.h" // and some elements67 // #def<strong>in</strong>e _CENTERED // disabled, to get the #else branch8 <strong>in</strong>t ma<strong>in</strong>()9 {10 // run the code us<strong>in</strong>g an exception handler, to11 // handle errors detected by the error checker12 try13 {14 // create the profile15 Profile* pProf = new Profile("Fl200x4");1617 // add conta<strong>in</strong>ers18 pProf->AddNodeConta<strong>in</strong>er(2);19 pProf->AddElementConta<strong>in</strong>er(1);2021 // create the Nodes (double symmetric)22 #ifdef _CENTERED23 Node* pN1 = new Node(1,0., 100.);24 Node* pN2 = new Node(2,0.,-100.);2526 #elif _SHIFTED27 // create the Nodes, shifted28 Node* pN1 = new Node(1,0., 0.);29 Node* pN2 = new Node(2,0.,-200.);3031 #else32 // create the Nodes, shifted and rotated33 Node* pN1 = new Node(1,0., 0.);34 Node* pN2 = new Node(2, 200./sqrt(2.),-200./sqrt(2.));35 #endif36 // create the Elements37 Element* pE1 = new Element(1,pN1,pN2,4.);3839 // add element40 pProf->AddElement(pE1);4142 // calculate the section values43 pProf->GetSectionValues();4445 // list profile data46 pProf->List();4748 // delete the profile49 delete pProf;50 }5152 // handle the errors throw<strong>in</strong>g str<strong>in</strong>g exceptsions7.8.2013


Page 158 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1353 catch(const char* str)54 {55 pr<strong>in</strong>tf("Exception: %s\n",str);56 }5758 // handle all unspecified exceptions59 catch(...)60 {61 pr<strong>in</strong>tf("Unknow exception!");62 }63 return 0;64 }The Output of the above discussed codeis given <strong>in</strong> figure 7.9. We see, that wecreate four <strong>in</strong>stances (two nodes, oneelement and one profile). We see thetest pr<strong>in</strong>t<strong>in</strong>g of there constructors.Then after hav<strong>in</strong>g assembled the profilethe section values are calculated andpr<strong>in</strong>ted. We see, that we get the samearea as <strong>in</strong> the case of the element check(section 7.2.5).The center of mas we get at the centerof the element, which ise x = 1 ( ) 2002 · √ = 70.712At the end we see, that we will get thesame values for the moment of <strong>in</strong>ertia<strong>in</strong> the ma<strong>in</strong> coord<strong>in</strong>ate system as wehave calculated <strong>in</strong> the case of the elementcheck. The calculated rotationangle is -45 ◦ as expected.Figure 7.9: Output of the Element Check ProgramE. Baeck


7.2. IMPLEMENTATION Page 1597.2.8 H-Profile Class for Model ProfilesA UML class diagram <strong>in</strong> figure 7.10 shows the concept of the classHProfile. The class is derived from the class Profile, whichitself is derived from the class Base. The only attributes the classHProfile gets, are the parameters to describe the profile’s geometry.BaseProfile• m_dh, the height,• m_dw, the width• m_dt, the flange thickness• m_ds, the web thicknessThe HProfile <strong>in</strong>stance is created with the call of the constructor,so we put the data check<strong>in</strong>g and the creation of the profile’s geometrydata <strong>in</strong>to the constructor. Therefore with one statement all the th<strong>in</strong>gsto do are done. We pass the name of the profile and it’s geometryparameter to the constructor.The HProfile class therefore will have the follow<strong>in</strong>g methods.HProfile+ m dh : double+ m dw : double+ m dt : double+ m ds : double+ HProfile(..) : −− ˜HProfile(): −+ Check(): <strong>in</strong>t+ Create() : <strong>in</strong>t+ List() : voidFigure 7.10: The Class HProfilemethode parameter type commentHProfileconstructorcNameconst char profile’s name, send to the base classdh double profile’s heightdw double profile’s widthdt double profile’s flange thicknessdw double profile’s weg thickness˜ProfileCheckCreateListdestructorchecks the parameter passed by the constructorcallcreate the geometry of the profile <strong>in</strong>terms of nodes and elementslist the profile’s data call<strong>in</strong>g the Listmethod of the base class tooIf errors are detected we give up runn<strong>in</strong>g backward us<strong>in</strong>g error codes. If an item is checked and an erroris detected an exception is thrown. So the apply<strong>in</strong>g rout<strong>in</strong>e has to catch the exception us<strong>in</strong>g the code ofthe profile with<strong>in</strong> a try block..7.8.2013


Page 160 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13The declaration of the class HProfile is given by the follow<strong>in</strong>g list<strong>in</strong>g.List<strong>in</strong>g 7.12: HProfile Class’s Header1 #ifndef HPROFILE_H_INCLUDED2 #def<strong>in</strong>e HPROFILE_H_INCLUDED34 #<strong>in</strong>clude "profile.h" // we have to know someth<strong>in</strong>g about Profile56 class HProfile : public Profile7 {8 public:910 HProfile(const char* pName, // profile’s name11 double dh, // height12 double dw, // width13 double dt, // thickness of the flanges14 double ds); // thickness of the web1516 <strong>in</strong>t Check(); // check the parameters17 <strong>in</strong>t Create(); // create the profile18 void List(); // list the data1920 // attributes: profile parameters21 double m_dh; // height22 double m_dw; // width23 double m_dt; // thickness of the flanges24 double m_ds; // thickness of the web25 };26 #endif // HPROFILE_H_INCLUDEDThe implementation code of the class HProfile is given below. Note, that constructor is used with it’sparameters to <strong>in</strong>itialize the HProfile data.List<strong>in</strong>g 7.13: HProfile Class’s Implementation1 #<strong>in</strong>clude "hprofile.h" // we need the HProfile header2 #<strong>in</strong>clude "node.h" // we will create Nodes3 #<strong>in</strong>clude "element.h" // and Elements4 #<strong>in</strong>clude 56 // constructor don’t forget to call the base classes constructor7 HProfile::HProfile(const char* pName,8 double dh, double dw, double dt, double ds) :9 Profile(pName)10 {11 // assign the <strong>in</strong>put data12 m_dh = dh;13 m_dw = dw;14 m_dt = dt;15 m_ds = ds;1617 // check the data18 Check();1920 // create the profile21 Create();E. Baeck


7.2. IMPLEMENTATION Page 16122 }2324 // Check the H-profile’s data, throw an exception if someth<strong>in</strong>g is not ok25 <strong>in</strong>t HProfile::Check()26 {27 double dEps = 0.5;28 if (m_dt < dEps) throw "error: dt <strong>in</strong>valid!";29 if (m_ds < dEps) throw "error: ds <strong>in</strong>valid!";30 if (m_dw < 2.*m_ds) throw "error: dw <strong>in</strong>valid!";31 if (m_dh < 3.*m_dt) throw "error: dh <strong>in</strong>valid!";32 return 1;33 }3435 // create the geometry36 <strong>in</strong>t HProfile::Create()37 {38 // add node and element space39 AddNodeConta<strong>in</strong>er(6); // for 6 nodes40 AddElementConta<strong>in</strong>er(5); // for 5 elements4142 // create nodes43 Node* pN[6];44 pN[0] = new Node(1,-m_dw/2., (m_dh-m_dt)/2.);45 pN[1] = new Node(2, 0., (m_dh-m_dt)/2.);46 pN[2] = new Node(3, m_dw/2., (m_dh-m_dt)/2.);47 pN[3] = new Node(4,-m_dw/2.,-(m_dh-m_dt)/2.);48 pN[4] = new Node(5, 0.,-(m_dh-m_dt)/2.);49 pN[5] = new Node(6, m_dw/2.,-(m_dh-m_dt)/2.);5051 // create elements52 Element* pE[5];53 pE[0] = new Element(1,pN[0],pN[1],m_dt); // bottom flange54 pE[1] = new Element(2,pN[1],pN[2],m_dt);55 pE[2] = new Element(3,pN[3],pN[4],m_dt); // top flange56 pE[3] = new Element(4,pN[4],pN[5],m_dt);57 pE[4] = new Element(5,pN[1],pN[4],m_ds); // web5859 // add elements to the profile60 for (<strong>in</strong>t i=0;i


Page 162 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 1378 AppendLog(m_pMsg);7980 // call the base class’s methode!81 Profile::List();82 }7.2.9 Check<strong>in</strong>g the HProfile ClassTo check the profile class, we implement a little test<strong>in</strong>g frame, which simple creates an profile to calculatethe section values of a HEA100 standard profile.The program executes the follow<strong>in</strong>g steps.• Allocate the HProfile <strong>in</strong>stances, specify<strong>in</strong>g all profile parameters.• Calculate the section values and• list the profiles data.• At the end we should not forget to clear the memory, delet<strong>in</strong>g the HProfile <strong>in</strong>stance.All the above discussed steps should be done with<strong>in</strong> a try block, so that we can handle detected errors<strong>in</strong> the follow<strong>in</strong>g catch blocks.• The first catch block will handle our exceptions, because we pass a const char* to theexception throw<strong>in</strong>g them.• The second catch block will handle all other exceptions. So, if we divide by zero or if we haveforgotten to check one case, the program is not crash<strong>in</strong>g, an unspecified exception is thrown.The code of the test<strong>in</strong>g frame is given below.List<strong>in</strong>g 7.14: Check Environment for the HProfile Class1 #<strong>in</strong>clude 2 #<strong>in</strong>clude 3 #<strong>in</strong>clude "hprofile.h" // we start with the hprofile45 <strong>in</strong>t ma<strong>in</strong>()6 {7 // run the code us<strong>in</strong>g an exception handler, to8 // handle errors detected by the error checker9 try10 {11 // check the H-Profile class12 HProfile* pProf = new HProfile("HEA-100",96.,100.,8.,5.);1314 // calculate the section values15 pProf->GetSectionValues();1617 // list profile data18 pProf->List();19E. Baeck


7.2. IMPLEMENTATION Page 16320 delete pProf;21 }2223 // handle the errors throw<strong>in</strong>g str<strong>in</strong>g exceptsions24 catch(const char* str)25 {26 pr<strong>in</strong>tf("Exception: %s\n",str);27 }2829 // handle all unspecified exceptions30 catch(...)31 {32 pr<strong>in</strong>tf("Unknow exception!");33 }34 return 0;35 }The Output of the above discussedcode is given <strong>in</strong> figure 7.11. We seethe <strong>in</strong>put data used and the coord<strong>in</strong>atesof the created nodes. Becausethe output given is rather long, wehave split this output <strong>in</strong>to the <strong>in</strong>putsection (upper picture) and the resultsection (lower picture).The lower figure shows the calculatedsection values. Because the orig<strong>in</strong> is<strong>in</strong> the center of the H-profile, we willnot get any eccentricity, i.e. static moments.If we use this symmetric orig<strong>in</strong>,we see that the moments of <strong>in</strong>ertiawith respect to our three coord<strong>in</strong>atensystems are the same.Figure 7.11: Output of the Element Check Program7.8.2013


Page 164 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13In the follow<strong>in</strong>g table we compare the calculated values with the values we will f<strong>in</strong>d <strong>in</strong> the book ofstandard profiles. 5 We see, that the values are on the secure side, i.e. the calculated values are smallerthan the exact value and the error <strong>in</strong> this case is less than 4%.value exact TWA error[cm 2 ] [cm 2 ] [%]area 21.2 20.4 −3.4big moment of <strong>in</strong>ertia 349 338 −3.3small moment of <strong>in</strong>ertia 134 133 -0.85 Areas are given <strong>in</strong> cm 2 and moments of <strong>in</strong>ertia are given <strong>in</strong> cm 4 , accord<strong>in</strong>g to German standard table books.E. Baeck


Part IIIAppendix165


Appendix AThe Console’s FriendsIf you want to work with a console w<strong>in</strong>dow, you should know the console’s best friends, the commandsto navigate through the folder tree, the commands to create, delete and chance directories, the commandsto setup paths and environment variables and commands to copy and delete files.And if you want to be happy us<strong>in</strong>g the console w<strong>in</strong>dow, it’s recommended to know someth<strong>in</strong>g aboutassembl<strong>in</strong>g so-called batch files, which are <strong>in</strong> the most simple k<strong>in</strong>d only a list of commands whichshould be executed without typ<strong>in</strong>g them a dozen times.The console w<strong>in</strong>dow can be created with the command cmd from the execution <strong>in</strong>put field <strong>in</strong> the startmenu of w<strong>in</strong>dows. A list of a lot of console commands is given by the command help 1 . If you need aspecific <strong>in</strong>formation related to a special command, you will get this <strong>in</strong>formation call<strong>in</strong>g the help with thecommand’s name as parameter.Geben Sie HELP ’Befehlsname’ e<strong>in</strong>, um weitere <strong>Info</strong>rmationen zu e<strong>in</strong>em bestimmtenBefehl anzugeigen.ASSOCATATTRIBBREAKCACLSCALLCDCHCPCHDIRCHKDSKCHKNTFSCLSCMDCOLORCOMPCOMPACTCONVERTZeigt Dateierweiterungszuordnungen an bzw. ändert sie.Legt e<strong>in</strong>e Zeit fest, zu der Befehle und Programme auf diesem Computerausgeführt werden.Zeigt Dateiattribute an bzw. ändert sie.Schaltet die erweiterte Überprüfung für STRG+C e<strong>in</strong> bzw. aus.Zeigt Datei-ACLs (Access Control List) an bzw. ändert sie.Ruft e<strong>in</strong>e Batchdatei aus e<strong>in</strong>er anderen Batchdatei heraus auf.Zeigt den Namen des aktuellen Verzeichnisses an bzw. ändert diesen.Zeigt die aktive Codepagenummer an bzw. legt diese fest.Zeigt den Namen des aktuellen Verzeichnisses an bzw. ändert diesen.Überprüft e<strong>in</strong>en Datenträger und zeigt e<strong>in</strong>en Statusbericht an.Zeigt die Überprüfung des Datenträgers beim Start an bzw. verändertsie.Löscht den Bildschirm<strong>in</strong>halt.Startet e<strong>in</strong>e neue Instanz des W<strong>in</strong>dows-Befehls<strong>in</strong>terpreters.Legt die H<strong>in</strong>tergrund- und Vordergrundfarben für die Konsole fest.Vergleicht den Inhalt zweier Dateien oder Sätze von Dateien.Zeigt die Komprimierung von Dateien auf NTFS-Partitionen an bzw.ändert diese.Konvertiert FAT-Volumes <strong>in</strong> NTFS. Das aktuelle Laufwerk kann nicht1 The list of commands is given <strong>in</strong> the language of the computer. So if you need an English version, try it on an Englishcomputer.167


Page 168 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13konvertiert werden.COPY Kopiert e<strong>in</strong>e oder mehrere Dateien an e<strong>in</strong>e andere Stelle.DATE Zeigt das Datum an bzw. legt dieses fest.DEL Löscht e<strong>in</strong>e oder mehrere Dateien.DIR Listet die Dateien und Unterverzeichnisse e<strong>in</strong>es Verzeichnisses auf.DISKCOMP Vergleicht den Inhalt von zwei Disketten.DISKCOPY Kopiert den Inhalt von e<strong>in</strong>er Diskette auf e<strong>in</strong>e andere Diskette.DOSKEY Bearbeitet Befehlse<strong>in</strong>gaben, ruft W<strong>in</strong>dows-Befehle zurückt understellt Macros.ECHO Zeigt Meldungen an bzw. schaltet die Befehlsanzeige e<strong>in</strong> oder aus.ENDLOCAL Beendet den lokalen Gültigkeitsbereich von Umgebungsänderungen <strong>in</strong>e<strong>in</strong>er Batchdatei.ERASE Löscht e<strong>in</strong>e oder mehrere Dateien.EXIT Beendet das Programm CMD.EXE (Befehls<strong>in</strong>terpreter).FC Vergleicht zwei oder mehr Sätze von Dateien und zeigt dieUnterschiede an.FIND Sucht e<strong>in</strong>e Zeichenkette <strong>in</strong> e<strong>in</strong>er oder mehreren Datei(en).FINDSTR Sucht Zeichenketten <strong>in</strong> Dateien.FOR Führt e<strong>in</strong>en angegebenen Befehl für jede Datei <strong>in</strong> e<strong>in</strong>em Dateiensatzaus.FORMAT Formatiert e<strong>in</strong>en Date<strong>in</strong>träger für die Verwendung mit W<strong>in</strong>dows.FTYPE Zeigt die Dateitypen an, die bei den Zuordnungen für dieentsprechenden Dateierweiterungen verwendet werden bzw. ändert sie.GOTO Setzt den W<strong>in</strong>dows-Befehls<strong>in</strong>terpreter auf e<strong>in</strong>e markierte Zeile <strong>in</strong>e<strong>in</strong>em Batchprogramm.GRAFTABL Ermöglicht W<strong>in</strong>dows, Sonderzeichen im Grafikmodus anzuzeigen.HELP Zeigt Hilfe<strong>in</strong>formationen zu W<strong>in</strong>dows-Befehlen an.IF Verarbeitet Ausdrücke <strong>in</strong> e<strong>in</strong>er Batchdatei abhängig von Bed<strong>in</strong>gungen.LABEL Erstellt, ändert oder löscht die Bezeichnung e<strong>in</strong>es Volumes.MD Erstellt e<strong>in</strong> VerzeichnisMKDIR Erstellt e<strong>in</strong> Verzeichnis.MODE Konfiguriert e<strong>in</strong> Systemgerät.MORE Zeigt Ausgabe auf dem Bildschirm seitenweise an.MOVE Verschiebt e<strong>in</strong> oder mehrere Dateien von e<strong>in</strong>em Verzeichnis <strong>in</strong>e<strong>in</strong> anderes.PATH Legt den Suchpfad für ausführbare Dateien fest oder zeigt diesen an.PAUSE Hält die Ausführung e<strong>in</strong>er Batchdatei an und zeigt e<strong>in</strong>e Meldung an.POPD Wechselt zu dem Verzeichnis, das durch PUSHD gespeichert wurde.PRINT Druckt e<strong>in</strong>e Textdatei.PROMPT Ändert die E<strong>in</strong>gabeaufforderung.PUSHD Speichert das aktuelle Verzeichnis, und wechselt dann zu e<strong>in</strong>emanderen Verzeichnis.RD Entfernt e<strong>in</strong> Verzeichnis.RECOVER Stellt lesbare Daten von e<strong>in</strong>em beschädigten Datenträger wieder her.REM Leitet Kommentare <strong>in</strong> e<strong>in</strong>er Batchdatei bzw. CONFIG.SYS e<strong>in</strong>.REN Benennt e<strong>in</strong>e Datei bzw. Dateien um.RENAME Bennent e<strong>in</strong>e Datei bzw. Dateien um.REPLACE Erstetzt Dateien.RMDIR Löscht e<strong>in</strong> Verzeichnis.SET Setzt oder löscht die Umgebungsvariablen bzw. zeigt sie an.SETLOCAL Beg<strong>in</strong>nt den lokalen Gültigkeitsbereich von Umgebungsänderungen <strong>in</strong>e<strong>in</strong>er Batchdatei.SHIFT Verändert die Position ersetzbarer Parameter <strong>in</strong> Batchdateien.SORT Sortiert die E<strong>in</strong>gabe.START Startet e<strong>in</strong> eigenes Fenster, um e<strong>in</strong> bestimmtes Programm oder e<strong>in</strong>enBefehl auszuführen.E. Baeck


A.1. DIRECTORY COMMANDS Page 169SUBSTTIMETITLETREETYPEVERVERIFYVOLXCOPYWeist e<strong>in</strong>em Pfad e<strong>in</strong>en Laufwerksbuchstaben zu.Zeigt die Systemzeit an bzw. legt sie fest.Legt den Fenstertitel für das E<strong>in</strong>gabeaufforderungsfenster fest.Zeigt die Ordnerstruktur e<strong>in</strong>es Laufwerks oder Pfads grafisch an.Zeigt den Inhalt e<strong>in</strong>er Textdatei an.Zeigt die W<strong>in</strong>dows-Version an.Legt fest, ob überwacht werden soll, ob Dateien korrekt auf denDatenträger geschrieben werden.Zeigt die Datenträgervolumebezeichnung und die Seriennummer an.Kopiert Dateien und Verzeichnisbäume.With<strong>in</strong> the follow<strong>in</strong>g sections some of the most important commands are discussed which are very helpful,if you are work<strong>in</strong>g with<strong>in</strong> the console w<strong>in</strong>dow. The command’s details should be studied from theorig<strong>in</strong>al literature too. With<strong>in</strong> this short scratch only the most important command options are discussed.A.1 Directory CommandsA.1.1Select<strong>in</strong>g a DriveSelect<strong>in</strong>g the active drive, the name of the drive should be given as command, like c: to select thestandard drive or d: to select the cd-rom or z: to select the user-drive on a computer of the computerpool.<strong>Info</strong>rmations of the drive are listet with the command vol.A.1.2List<strong>in</strong>g the Content of a DirectoryTo list the content of an directory we can use the command dir. dir lists all files and subdirectories of theactual directory. You can also call the dir command with some wildcards filter<strong>in</strong>g. Figure A.1 shows adirectory list us<strong>in</strong>g a wildcard 2 filter<strong>in</strong>g of *.pdf. Note, that the volume <strong>in</strong>formation of the actual driveis also listed. We will get the same list<strong>in</strong>g, if we use the absolute path of the desired directory and startthe command from anywhere.dir c:\CM\Cm-CLFE\BookOfExamples\*.pdfFigure A.1: Create a Directory List of all pdf Files2 A wildcard is a joker or a filter def<strong>in</strong>ition for a command. * means everth<strong>in</strong>g with<strong>in</strong> one section of a file name <strong>in</strong> betweendots. A ? character is a joker for only one character with<strong>in</strong> a str<strong>in</strong>g. So the wildcards t?st.* would filter a file with the nametest.pdf or tost.noth<strong>in</strong>g .7.8.2013


Page 170 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13A.1.3Creat<strong>in</strong>g and Remov<strong>in</strong>g a DirectoryA directory can simply be created with the command mkdir. Figure A.2 shows <strong>in</strong> the first step a directorylist of the directory c:\cm\commands. Then a new directory is created with the name commands.After that the creation is checked with a further dir call. You can remove the directory with the <strong>in</strong>versecommand rmdir.Figure A.2: Create a DirectoryA.1.4Brows<strong>in</strong>g through DirectoriesTo browse through directories you can use the command cd, which is also called change directory.With the command cd .. you step one level up to the root directory. You can specify the directoriesname relative then you will jump out from the actual directory to the specified. You also can specifythe directories name absolute. Then you will jump from the roots directory <strong>in</strong>to the specified. FigureA.3 shows, that we start <strong>in</strong> the root directory. Then we clime up with relative jumps <strong>in</strong>to the directoryc:\cm, c:\cm\commands and at last c:\cm\commands\test. After that we jump backwith one jump <strong>in</strong>to the root with cd \ and then back <strong>in</strong> our test directory with an absolute jumpcd \cm\commands\test.Figure A.3: Brows<strong>in</strong>g through the DirectoriesE. Baeck


A.2. FILE COMMANDS Page 171A.2 File CommandsHow can we check the content of a file with a simple command. You can use the type command. FigureA.4 shows how to pipe 3 a screen stream <strong>in</strong>to a file. This can be done by us<strong>in</strong>g a pipe character >.With<strong>in</strong> a first step the directory list of the actual directory is created with the dir command. This list ispiped <strong>in</strong>to a file with the name dir.lst us<strong>in</strong>g the command dir > dir.lst. After hav<strong>in</strong>g createdthe text file with the directory list this list is viewed by the command type. If you have to list largerfiles with a lot of l<strong>in</strong>es, you can use the command more to give a list page by page. So you have topipe the output of the type command <strong>in</strong>to the postprocess<strong>in</strong>g more command by us<strong>in</strong>g the commandtype longfile.txt | more.Figure A.4: Create a DirectoryTo delete a file the command del can be used. Figure A.5 shows <strong>in</strong> the first step a directory list. Two filesare found <strong>in</strong> the directory, dir.lst and helloworld.f90. In the second step the file dir.lst isdeleted by the command del dir.lst. This is shown <strong>in</strong> the third step giv<strong>in</strong>g an actual directory listwith the command dir. You can also use wildcards with<strong>in</strong> the del command, so you can delete all filesfrom the directory with the wildcard *.*, so <strong>in</strong> this case we use the command del *.*.Figure A.5: Create a Directory3 Pipe means, that a output stream of one process is used as an <strong>in</strong>put stream for a follow<strong>in</strong>g process, | character, or is used as<strong>in</strong>put stream for a file, > character.7.8.2013


Page 172 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13A.3 Environment CommandsOne of the most important environment commands is the command path which is used to specify thesearch path for the executables. If you want to execute a program from the command l<strong>in</strong>e, it should beaccessible by the command executer. Therefore the command path should be used to extend the standardpath by the access path of the desired program.If we want to use the compiler gfortran.exe, which lives <strong>in</strong> the folder c:\programs\m<strong>in</strong>gw\b<strong>in</strong> weshould use the follow<strong>in</strong>g command to extend the search path.path = %path%;c:\programs\m<strong>in</strong>gw\b<strong>in</strong>%path% sets the still active path, which should not be overwitten by the extension.If you want to check the actual path, then the command path can be given without parameters (see figureA.6). The figure shows that the M<strong>in</strong>GW\b<strong>in</strong> is set and that the <strong>in</strong>stalled compiler g95.exe was found.Figure A.6: Check<strong>in</strong>g the System PathPlease note, that no quotes are used to specify the search path of the M<strong>in</strong>GW package, even if there arespace characters <strong>in</strong>side the path name. It is astonish<strong>in</strong>g, that the compiler executable is found, if quotesare used, but the secondary processes can obviously not be executed, so that you will get the follow<strong>in</strong>gerror message (see figure A.7), if the compiler should compile a source file.Figure A.7: Compiler Error due to wrong Path Sett<strong>in</strong>gsE. Baeck


Appendix BCode::Blocks’s first ProjectWith<strong>in</strong> this chapter the creation of a project with the Code::Blocks IDE for Fortran is discussed as wellas the sett<strong>in</strong>gs which are essential (see also section 5.1).A new project can be created follow<strong>in</strong>g the steps discussed below.1. Start the IDETo create a project we start the Code::Blocks application (see figure 1.9).2. Check the Toolcha<strong>in</strong>Because the Code::Blocks IDE is a general IDE for a set of compilers, we have to setup theparameters for the toolcha<strong>in</strong> executable. Especial the compiler’s root directory has to be fitted (seefigure 1.10).3. Start new ProjectClick on the l<strong>in</strong>k Create a new project.4. Select the Fortran TemplateFigure B.1 shows the selection of the template to <strong>in</strong>itialize the new project.5. Setup the Project’s Name and it’s FolderTo setup the project’s name and folder, we have to fill <strong>in</strong> the project’s name <strong>in</strong>to the first editcontrol (see figure B.2). The second edit contents the root folder of our project. We can use thebrowser control - the button with the three dots - to browse the folder tree. The third edit contentsthe project file. The file name is created automatically. The whole project file with the total path iscreated with<strong>in</strong> the fourth edit.6. Setup the Project’s ConfigurationClick<strong>in</strong>g on next we will see the form to specify the project’s configuration (see figure B.3). Note,that is very important to select the proper compiler <strong>in</strong> the first combo. Please select the GNUFortran Compiler. If the proper compiler is not selected, the build cha<strong>in</strong> will crash with a strangeerror message. It’s recommended to use the standard configurations release and debug. If thesoftware will work properly, you can build the release version of your software for shipp<strong>in</strong>g. If thesoftware is work<strong>in</strong>g faultily or bad the debug version can be used to f<strong>in</strong>d the software bugs withthe debugger tool.173


Page 174 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure B.1: Select the Fortran TemplateFigure B.2: Setup the Project’s Name and Folder7. Project’s Wizard f<strong>in</strong>ishedIf we click on f<strong>in</strong>ish, the wizard is closed and we will see the project with<strong>in</strong> the IDE’s projectbrowser (see figure B.4). If we open the node Fortran Sources, we f<strong>in</strong>d a source module calledhello.f90.8. Rename the hello by a mean<strong>in</strong>gful NameTo use a mean<strong>in</strong>gful name for our ma<strong>in</strong> module we have to rename the hello.f90 by simply click<strong>in</strong>gright on it. You select the rename item from the context menu and will get a small form to overwritethe hello.f90 (see figure B.5). So we overwrite the default name by LittleProjectMa<strong>in</strong>.f90.E. Baeck


Page 175Figure B.3: Setup the Project’s ConfigurationFigure B.4: The Project now is created9. Open the Ma<strong>in</strong> ModuleA module’s source can be loaded <strong>in</strong>to the editor by double click<strong>in</strong>g it <strong>in</strong> the source folder tree.Figure B.6 shows the content of the default source of the renamed module.7.8.2013


Page 176 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure B.5: Overwrit<strong>in</strong>g the default source filenameFigure B.6: Open the Ma<strong>in</strong> ModuleE. Baeck


Page 17710. Overwrite the Module SourceAfter hav<strong>in</strong>g opend the ma<strong>in</strong> module, we can overwrite it’s source. In l<strong>in</strong>e 6 we implement a callto the subrout<strong>in</strong>e MySubModule. This source lives <strong>in</strong> a second module, which should be createdas follows. Figure B.7 shows the overwritten source of the ma<strong>in</strong> module.Figure B.7: Overwrit<strong>in</strong>g the Ma<strong>in</strong> Module’s Source11. Create a new Module for the Subrout<strong>in</strong>eTo create a new source file, a new module we use the command file/New/empty file from the ma<strong>in</strong>menu. The new source file is <strong>in</strong>itialized with a standard name, <strong>in</strong> our case with untitled1. So weare asked, whether we want to add this new source to our project. The answer should be yes (seefigure B.8).12. Save the new Module us<strong>in</strong>g a mean<strong>in</strong>gful NameAfter hav<strong>in</strong>g added the new module to our project, we should specify the name of the new modulewith<strong>in</strong> the standard save as dialog (see figure B.9).13. Setup the Configuration for the new ModuleBefore we can start to write the new module’s source we have to set up it’s configuration. Weselect both configurations, the release and the debug configuration (see figure B.10).14. Writ<strong>in</strong>g the new Module’s SourceAfter hav<strong>in</strong>g <strong>in</strong>stalled the new module for our project we can double click it’s node with<strong>in</strong> thesource module tree and load it <strong>in</strong>to the IDE’s editor. Because we want to show how to work withmore than one module our ma<strong>in</strong> program should call the subrout<strong>in</strong>e MySubModule which onlyshould pr<strong>in</strong>t the content of it’s <strong>in</strong>put str<strong>in</strong>g parameter. Figure B.11 shows the source of the submodule.15. Build the ExecutableThe executable now can be build by the command Build/Build from the ma<strong>in</strong> menu or by theacceleration key Ctrl-F9. If you have executed the build you should see a build log like <strong>in</strong> figure7.8.2013


Page 178 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure B.8: Start<strong>in</strong>g with a new ModuleFigure B.9: Save the new Module specify<strong>in</strong>g it’s nameB.12 <strong>in</strong> the build log w<strong>in</strong>dow. Before a total build is executed it is recommended to check andcompile each module for it’s own by the acceleration key Ctrl-Shift-F9.16. Execut<strong>in</strong>g the ExecutableThe executable can be started from the IDE with the command Build/Run or by usage of theacceleration key Ctrl-F10. The programm starts with<strong>in</strong> a command w<strong>in</strong>dow and will pr<strong>in</strong>t it’soutput (see figure B.13).E. Baeck


Page 179Figure B.10: Select the Configurations to supportFigure B.11: Writ<strong>in</strong>g the Sub Module’s Source7.8.2013


Page 180 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13Figure B.12: Check the Output <strong>in</strong>t the Build Log W<strong>in</strong>dowFigure B.13: Result of our little ProjectE. Baeck


Appendix CSome TheoryC.1 Section PropertiesWith<strong>in</strong> this chapter the formulas for the section properties of a th<strong>in</strong> walled model are given.A th<strong>in</strong> walled model for a profile section consists of a set of l<strong>in</strong>es which describes the profile sectiongeometry at the centerl<strong>in</strong>e.C.1.1The Area of a Profile SectionThe Area is approximately the sum of the areas of the l<strong>in</strong>es of the th<strong>in</strong> walled model.∫A =Ae µ · dA ≈n∑e µ,i · L i · t ii=1(C.1)with: L i the length of l<strong>in</strong>e it ie µ,ithe thickness of l<strong>in</strong>e ithe relative elasticity of l<strong>in</strong>e i (1 for only one material)C.1.2First Moments of an AreaThe first moments of an area are the area <strong>in</strong>tegrals given below. The (y,z) values are related to an givencoord<strong>in</strong>ate system.∫S y =∫S z =AAe µ · z · dA ≈e µ · y · dA ≈with: A i the area of a l<strong>in</strong>e iy iz <strong>in</strong>∑e µ,i · z i · A ii=1n∑e µ,i · y i · A ii=1the y coord<strong>in</strong>ate of the center of l<strong>in</strong>e ithe z coord<strong>in</strong>ate of the center of l<strong>in</strong>e i(C.2)181


Page 182 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13C.1.3Second Moments of an Area or Moments of InertiaThe moments of <strong>in</strong>ertia can be calculated with the formulas below. If we have a given arbitrary coord<strong>in</strong>atesystem <strong>in</strong> general we have three values of <strong>in</strong>ertia the I y , the I z and the mixed I yz . If we use the ma<strong>in</strong>coord<strong>in</strong>ate system, the mixed moment of <strong>in</strong>ertia is vanish<strong>in</strong>g, so we use the symbols I ξ and I η .∫I y =∫I z =∫I yz =AAAe µ · z 2 · dA ≈e µ · y 2 · dA ≈e µ · y · z · dA ≈n∑i=1e µ,i · (( (z b,i − z a,i ) 2 /12) + z 2 ) )i · A<strong>in</strong>∑e µ,i · (( (y b,i − y a,i ) 2 /12) + y 2 )i ·) A ii=1n∑e µ,i · (((y b,i − y a,i )(z b,i − z a,i )/12) + y i · z i ) · A i )i=1(C.3)with: A iy iz iy a,iz a,iy b,iz b,ithe area of a l<strong>in</strong>e ithe y coord<strong>in</strong>ate of the center of l<strong>in</strong>e ithe z coord<strong>in</strong>ate of the center of l<strong>in</strong>e ithe y coord<strong>in</strong>ate of the first po<strong>in</strong>t of l<strong>in</strong>e ithe z coord<strong>in</strong>ate of the first po<strong>in</strong>t of l<strong>in</strong>e ithe y coord<strong>in</strong>ate of the second po<strong>in</strong>t of l<strong>in</strong>e ithe z coord<strong>in</strong>ate of the second po<strong>in</strong>t of l<strong>in</strong>e iTo solve an <strong>in</strong>tegral like I y = ∫ A z 2 · dA for a polyl<strong>in</strong>e we can split up the <strong>in</strong>tegral <strong>in</strong>to the sum of<strong>in</strong>tegrals over the polyl<strong>in</strong>e segments.∫I y =Az 2 · dA =n∑∫i=1A iz 2 · dATo solve an <strong>in</strong>tegral for a polyl<strong>in</strong>e segment we simple calculate it for the center of mass, because a simpleshift only will give us an additional term, the Ste<strong>in</strong>er term. If we now want to calculate the polyl<strong>in</strong>e<strong>in</strong>tegral at the center of mass we rotate the coord<strong>in</strong>ate system by an angle ϕ <strong>in</strong>to the l<strong>in</strong>e’s longitud<strong>in</strong>aldirection, because the transversal dimension, the thickness, is constant and so the respective <strong>in</strong>tegral willbe trivial.(C.4)E. Baeck


C.1. SECTION PROPERTIES Page 183Thus we make the follow<strong>in</strong>g substitution.(y, z) ⇒ (η, ξ)z = ξ/cos(ϕ)(C.5)(C.6)With this substitution we will get the follow<strong>in</strong>g <strong>in</strong>tegral.I y,i =∫ η=+t ∫ ξ=+L/2= t ·η=−t ξ=−L/2∫ ξ=+L/2ξ=−L/2ξ 2· dη · dξcos(ϕ) 2ξ 2cos(ϕ) 2 · dξ∣= t · ξ33 · 1 ∣∣∣ξ=+L/2cos(ϕ) 2 ξ=−L/2= t · L312 · 1cos(ϕ) 2= (z b,i − z a,i ) 212· A i with t · L = A i (C.7)C.1.4Center of MassThe coord<strong>in</strong>ates of the center of mass are calculated with the arithmetic mean. Because the numerator ofthe arithmetic mean is identical with the first moment of the area (see section C.1.2) and the denom<strong>in</strong>atoris identical with the area of the profile, which is calculated <strong>in</strong> section C.1.1 we can use this values.∫Ay c = ∫y · dAA dA = S zA∫z c =A∫z · dAA dA= S yA(C.8)C.1.5Moments of Inertia with Respect to the Center of MassIf we know the center of mass coord<strong>in</strong>ates given <strong>in</strong> section C.1.4 we can calculate the moments of <strong>in</strong>ertiawith respect to the center of mass us<strong>in</strong>g Ste<strong>in</strong>er’s Theorem as follows.I y,c = I y − z 2 c · AI z ,c = I z − y 2 c · AI yz ,c = I yz − y c · z c · A(C.9)7.8.2013


Page 184 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13C.1.6Ma<strong>in</strong> Axis TransformationTo get the moments of <strong>in</strong>ertia I ξ and I η we have to transform the moments of <strong>in</strong>ertia <strong>in</strong>to the ma<strong>in</strong>coord<strong>in</strong>ate system. Us<strong>in</strong>g this coord<strong>in</strong>ate system the mixed moment of <strong>in</strong>ertia is vanish<strong>in</strong>g.The ma<strong>in</strong> axis transformation is given with equation C.10. 1I del = I y,c − I z ,cI sum = I y,c + I z ,c√I sqr = IDel 2 + 4 · I yz 2 ,cϕ = 1 2 · arctan(2 · I yz ,cI del)I ξ = 1 2 · (I sum + I sqr )I η = 1 2 · (I sum − I sqr )(C.10)1 The rotation angle ϕ should be shifted <strong>in</strong>to the <strong>in</strong>tervall [−π/2... + π/2]. To avoid a zero division calculat<strong>in</strong>g the rotationangle ϕ a special version of the atan function should be used, which is able to handle the pole problem. In Python like <strong>in</strong> C thisfunction is called atan2(y, x), which calculates the atan( y ). xE. Baeck


Bibliography[1] Photo: Lawrence Livermore National Laboratory(L<strong>in</strong>k: http://www.columbia.edu/acis/history/704.html)[2] Watcom FORTRAN 77 Language Reference Edition 11.0c[3] Stefen J. ChapmanFortran 90/95 for Scientists and Eng<strong>in</strong>eers, Second EditionMcGraw-Hill, 2004[4] H.R. Schwarz, N. KöcklerNumerische MathematikBI Wissenschaftsverlag Mannheim/Wien/Zürich, 1988[5] Wikipedia, The Free Encyclopedia[6] cplusplus.com - The C++ Resources Networkhttp://www.cplusplus.com/[7] ISO/IEC 19501:2005<strong>Info</strong>rmation technology – Open Distributed Process<strong>in</strong>g – Unified Model<strong>in</strong>g Language(UML) Version 1.4.2185


Index.AND., 26.EG., 25.EQU., 26.FALSE., 26.GE., 25.GT., 25.LE., 25.LT., 25.NE., 25.NEQU., 26.NOT., 26.OR., 26.TRUE., 262GB, 20A format, 28area, 181arithmetic mean, 183array, 42automatic, 43dynamical, 43static, 42assembler, 6backward substitution, 89base class, 133b<strong>in</strong>ary numbers, 20block data, 49build, 14, 177bytecode, 6C, 5, 7, 115C++, 5, 115C/C++ projects, 111C#, 5CALL, 69card punch, 8catch, 127, 148, 159cd, 170center of mass, 183channel, 27CLOSE, 76cmd, 167Code::Blocks, 9, 13, 173columns, 18COMMON, 85common, 49compiler, 5complement, 20complex, 20console w<strong>in</strong>dow, 167conta<strong>in</strong>s, 50CONTINUE, 29CYCLE, 29CYGWIN, 12debugger, 10del, 171derivative, 57, 59dir, 169, 171DO, 29double, 123DOUBLE PRECISION, 21E format, 28editor, 9, 13encapsulat<strong>in</strong>g, 92END DO, 29end function, 40end subrout<strong>in</strong>e, 41exception, 127, 148, 159EXIT, 29exponent, 34extension, 13F format, 28factorial, 33FB substitution, 101Fibunacci numbers, 6first moment, 181186


INDEX Page 187fixed format, 18float, 20formal parameters, 40FORMAT, 28Forth, 6FORTRAN 2008, 7FORTRAN I, 7FORTRAN II, 7FORTRAN IV, 7Fortran66, 29, 30, 34, 53Fortran77, 18–20, 29, 30Fortran90/95, 18–20, 30forward substitution, 89free format, 18free FORTRAN compiler, 13free FORTRAN tools, 9function, 40G95, 9, 17, 172GCC C++ compiler, 112GFortran, 17, 172Grace Hopper, 7I format, 28IBM Type704, 7IDE, 9IF, 34INCLUDE, 69<strong>Info</strong><strong>Server</strong>, 17<strong>in</strong>put parameters, 40<strong>in</strong>teger, 19INTEGER*2, 21INTEGER*4, 21<strong>in</strong>terpreter, 5ISML, 7iteration, 57label, 29l<strong>in</strong>ear equation system, 89, 102LINUX, 5, 12LOGICAL*1, 21LOGICAL*2, 21mach<strong>in</strong>e code, 6ma<strong>in</strong> axis, 184ma<strong>in</strong> function, 120memory manager, 90MFC, 130M<strong>in</strong>GW, 9, 12, 172mkdir, 170module, 49moment of <strong>in</strong>ertia, 182MS Excel, 33NAG, 7negative numbers, 20new, 139Newton, 42Newton’s Algorithm, 59OOP, 129OPEN, 76output parameters, 40parent class, 133path, 172permissions, 131pip<strong>in</strong>g, 171private, 131program structure, 17protected, 131public, 131punch card and 80, 8Python, 6quadratic equation, 35READ, 26, 69, 76REAL*8, 21return, 120return code, 127rmdir, 170run, 178second moment, 182Smalltalk, 6SUBROUTINE, 69subrout<strong>in</strong>e, 40suffixcpp, 130h, 130superclass, 133the most famous code, 53throw, 127, 148, 1597.8.2013


Page 188 Computer Languages for Eng<strong>in</strong>eer<strong>in</strong>g - SS 13try, 127, 148, 159type, 171UML, 129aggregation, 130class diagram, 129composition, 130<strong>in</strong>heritance diagram, 129note diagram, 129note diagram assignment, 129unicode, 19UNIX, 12upper lower extractor, 69VBA, 5virtual mach<strong>in</strong>e, 5vol, 169Watcom, 9, 17W<strong>in</strong>dows32, 20WRITE, 26X format, 28E. Baeck

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!