New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Introduction to Computing

by: Jaden Jakubowski

Introduction to Computing CSC 112

Jaden Jakubowski
GPA 3.94

Robert Rodman

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Robert Rodman
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 120 page Class Notes was uploaded by Jaden Jakubowski on Thursday October 15, 2015. The Class Notes belongs to CSC 112 at North Carolina State University taught by Robert Rodman in Fall. Since its upload, it has received 7 views. For similar materials see /class/223806/csc-112-north-carolina-state-university in ComputerScienence at North Carolina State University.

Similar to CSC 112 at NCS


Reviews for Introduction to Computing


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/15/15
Computer Architecture Moore39s Law CPU Circuits Double Every 2 Years 10000 Clock Speed 1000 Pentium 4 Mhz Pentium H IH 100 Pentium I 10 1 Also works for CPU speed You can see that since 1988 around when many ofyou were born there have been 10 doublings from 106 to 109 21 103 mow mar ummn39 z Dwain hm39llanhm39zwnmssnr MOORE39S LAW my grlum ho bw39 mar mumu imm Mml39nvuum Ilnxnxm mm39 WWWEu muss Frans melsas mesxu 15 1995 anau Ions 701 r 1910 ms znus znnn 19m I955 man Iranslsmrs Ionnaaannnn Lunnnnuoun mmnamm mun zmn WHAT IS A C OlVIPUTER THESE quotDEFINITIONSquot ARE JUST A FEW OF MANY FOUND ON THE WEB A quotcomputerquot is defined for Current Population Surveys as a personal or home workstation having a typewriterlike keyboard connected to a laptop computer minicomputer or mainframe computer wwwntiadocgovntiahomefttn99glossaghtml An quotelectronic deVice that accepts information in digital or similar form and manipulates it for a result based on a sequence of instructions quot UCITA l 02a9 euroecomcmueduresourceselibrageclglossshtml Any deVice capable of processing information to produce a desired result No matter how large or small they are computers typically perform their work in three welldefined steps 1 accepting input 2 processing the input according to predefined rules programs and 3 producing output wwwmicrosoftcomtechnetprodtechnolVisioVisioZOOZplanglossammspx A computer is a machine that accepts data in digital form and manipulates it for some result based on a program sequence of instructionswhich describes how data is to be manipulated or processed www southbendtechpurdueeduacademicsdegreesCPTHtmlcptterminol ogyhtml A program that performs one of the tasks for which a computer is used such as word processing or numerical computations wwweconomicadventureorgteachersglossamdeccfm A deVice or system that is capable of carrying out a sequence of operations in defined manner The operations are frequently numeric computations or data manipulations but also include data input and output wwwmcccommneteduHermesWebApppageFactory An electronic unit that receives information data from sensors processes the information then performs the function it was programmed to do Generally this function is in the form of an output or command home swipnet sew 651 89glossamhtm A multifunction electronic deVice that can execute instructions to perform a task WWWbinarygraphicscomglossa hardwarehtml KEY WORDS DEVICE AlACHINE SYSTEM ELECTRONIC DIGITAL OPERATIONS INF ORZWATION DATA PROGRAM INPUT OUTPUT INPUT 9 OPERATIONS 9 OUTPUT WHERE INPUT IS INFORMATION OR DATA IN A DIGITAL FORMAT OPERATIONS TREAT THE INPUT ACCORDING TO A PROGRAM AND BASED ON THAT PROGRAM OUTPUT IS PRODUCED THAT IS ALSO INFORMATION OR DATA Computer System a set of components organized to perform a task Input Process Output Machine Instruction Set The essence of computing is that Fancy and complicated actions are just built from executing very simple instructions add sub multiply divide move at a very fast rate LET39S DELVE INTO THE GUTS OFA COMPUTER WHICH ON THE LARGEST POSSIBLE SCALE HAVE REMAINED MUCH THE SAME SINCE THE 194039s THOUGH THE INDIVIDUAL COMPONENTS HAVE OF COURSE IMPROVES DRAMATICALLY SINCE THAT TIME John von N eumann Architecture circa 1944 Main Memory CPU Machine Control A Instructions 39 Unit L amp Buses U Data Wires that connect SO WHAT ARE THE quotBIGquot PIECES ON THE LARGEST SCALE WE HAVE CONIPUTER Interconnection Central Processing Unit The Computer TopLevel Structure unchanged since 194039s CPU THE WORKHORSE OF THE SYSTEM IT CONTAINS A CONTROL UNIT THAT SUPERVISES DATA MOVEMENT AN ARI THMETI CLOGI C UNIT ALU THAT WELL DOES ARITHMETIC AND LOGIC WHICH ARE THE BASES OF ALL COMPUTATION IT ALSO CONTAINS REGISTERS WHICH HOLD SMALL CHUNKS OF DATA AND FINALLY BUSES WHICH ACT AS CONDUITS INTER CONNECTING ALL THE PIECES TO ONE ANOTHER HERE39S A PICTURE Iunit Instruction Unit Eunit Execution Unit CPU Control Unit Address of next instruction ALU I unit E unit Fetch next Control logic instruction for each 0 Decode instruction Pass control to E unit MulDiv M Arithmetic and C Registers gic Unit Internal CPU Interconnection Control Unit The Central Processing Unit CPU WE39LL LOOK MORE CLOSELY AT THE ALU A BIT LATER THE OTHER ESSENTIAL COMPONENT OF THE CPU IS THE CONTROL UNIT IT TELLS THE COMPUTER WHAT SMALL STEP TO TAKE NEXT IT GRABS AN INSTRUCTION FROM CONTROL MEMORY DECODES IT SEES THAT IT39S CARRIED OUT BY PERHAPS COMMUNICATING WITH THE ALU AND DETERMINES FROM WHERE IN MEMORY TO GRAB THE NEXT INSTRUCTION WHAT IS CALLED quotSEQUENCING LOGIC quot HERE39S A PICTURE OF IT That is the fetch execute cycle 01 Sequencing Logic But this picture is becoming obsolete as more and more parallel architectures evolve Bus w Sequencing Logic Control Unit Registers and Decoders Control Memory Figure 16 The Control Unit Pipelining and Hyperthreading may occur Back to the larger View and Main Memory COMPUTER Interconnection Central Processing Unit The Computer TopLevel Structure unchanged since 194039s MAIN MEMORY MAY BE LIKENED UNTO A LARGE CITY MADE UP OF UNIFORM HOUSES EACH WITH ITS OWN UNIQUE ADDRESS EACH HOUSE CONTAINS 8 RESIDENTS EACH OF WHOM IS A BINARY DIGIT OR m EITHER 0 OR 1 THIS FAMILY UNIT IS CALLED A BYTE THE CITY IS COMMONLY ORGANIZED INTO BLOCKS OF 4 OR 8 HOUSES CALLED WORDS AND POSSIBLY LARGER SUBDIVISIONS ANALOGOUS TO quotGATED COMMUNITIESquot WHICH HAVE RESTRICTED ACCESS USED TO quotPROTECTquot PRECIOUS INFORMATION SUCH AS THE OPERATING SYSTEM HIGH MEMORY WHERE THE RICH LIVE LOW MEMORY FOR STUDENT HOUSING COMMON AREAS WHERE ANYBODY CAN LIVE AND Sp ON Size pre xes K Kilo M Mega G Giga T Tera 210 220 230 240 z thousand 3 million z billion z trillion REGISTERS ARE ELITE COMMUNITIES COMPRISING BLOCKS OF 32 OR 64 HOUSES EACH CONTAINING A SINGLE BIT EACH WITH ITS OWN ADDRESS WITHIN THE REGISTER THESE FIRST CLASS CITIZENS ARE RECRUITED FROM MAIN MEMORY AND LIVE TENIPORARILY IN LUXURY SO THEY MAY BE ACCESSED QUICKLY WITHOUT HAVING TO N EGOTIATE DOWNTOWN TRAFFIC AS IT WERE HERE IS A quotREAL WORLDquot OR LEASTWISE A MORE REAL WORLD PICTURE OF WHAT WE39VE BEEN TALKING ABOUT Computer es PC Architecture pc Block Diagram HERE is a brief summary schematic block diagram of a typical Personal Computer 1 Relationships are shown between the CPU Central Processing Unit DRAM Qynamic Random Access Memory local bus and the peripherals which conne t to the motherboard The ISA ystem Interface bus PCI geripheral Component Interface bus and USB Qniversal eria ns bus are shown Some typical PC parameters are given along with a Graphics Resolution chart Otherjargon SRAMSynchronous RAM EISAExtended or Enhanced ISA IDEIntegrated Drive Electronics BIosBasic Input Output System MCIAZPeripheral Component MicroChannel Interconnect Archimcture PCMCIAPeople Can39t Memorize Computer Industry Acronyms VaugnnslPagerscam z 5 m PC Block Diagram mm quotmquot Hmmmm We Peripherals samlumannmmm amazrmadurensw mum 3mm mean mmwmem 25 m as h Wrgued pan parguaw M PEI bus USE bus A u SCSI bus IDE bus mm mm m A munk y m N r 2 m m Vquot mm nu ma NOTE THE FOUR BIG PIECES CPU MAIN MEMORY INPUTOUTPUT AND SYSTEM INTERCONNECTIONS OR BUSES Mother board PC components CPU Math Coprocessor SRAM cache DRAM Video RAM BIOS ROM PC1 1311 ge Peripherals Monitor Keyboard Mouse EISA Hard Drive Floppy Disk CD ROM printer scanner USB drive Graphics Resolution Table pixels EGA 640 X 350 Enhanced Graphics Adaptor VGA 640 X 480 Vldeo Graphics Array SVGA 800 X 600 Super VGA XGAXVGA 1024 X 768 eXtended GAVGA SXGA 1280 X 1024 Super eXtended GA UXGA 1600 X 1200 Ultra XGA In case this is overwhelming here are the rst few entries in the quotAcknowledgementquot invoice of a computer I purchased a few years ago copied verbatim this could happen to you too Dimension 4700 Series Intel Pentium 4 Processor 550 with HT Technology 34GHz 1 GB DDR2 SDRAM at 400MHz I28MB PCI Express x16 D VI VGA T Vout AT I Radeon X3 00 SE 160 GB Serial ATA Hard Drive 7200RPM Now even with all the acronyms we39ve seen we are or leastwise I am slightly clueless until a little research reveals HTHyperThreading DDR2Double Data Rate 2nd generation SDRAMSynchronous Dynamic RAM DVIDigital Visual Interface ATIATI Technologies a manufacturer of video cards in particular the Radeon X300 SE ATA Advanced Technology Attachment OF COURSE IT S NOT CLEAR THAT THIS IS MUCH HELP AFTER ALL WHAT DOES DOUBLE DATA RATE 2ND GENERATION TELL IVIE THAT S USEFUL BUT THERE YOU GO MORE RESEARCH IS NEEDED OR YOU JUST TRUST THE IVIERCHANT Introduction to FORTRAN Fortran is a language used to tell a computer What to do What is a computer 0 A multifunction electronic device that can execute instructions to perform a task 0 A computer is a machine that accepts data in digital form and manipulates it for some result based on a program sequence of instructionswhich describes how data is to be manipulated or processed 0 A device or system that is capable of carrying out a sequence of operations in defined manner The operations are frequently numeric computations or data manipulations but also include data input and output Key Words Device Machine System Electronic Digital Operations Information Data Program Input Output INPUT 9 OPERATIONS 9 OUTPUT WHERE INPUT IS INFORMATION OR DATA IN A DIGITAL FORMAT OPERATIONS TREAT THE INPUT ACCORDING TO A PROGRAM AND BASED ON THAT PROGRAM OUTPUT IS PRODUCED THAT IS ALSO INFORMATION OR DATA Computer System a set of components organized to perform a task Input Process Output gt Machine Instruction Set The essence of computing is that Fancy and complicated actions are just built from executing very simple instructions add sub multiply divide move at a very fast rate m is a language used to tell a computer What to do Languages have syntax or grammar English Correct or grammatical The dog chased the cat Incorrect or ungrammatical Chased dog the cat the Fortran Correct syntaX abcde Incorrect syntaX abcde Languages have semantics or meaning The dog chased the cat means A certain kind of animal with canine properties ran purposefully toward another kind of animal with feline properties that was attempting to escape abcde causes the Fortran compiler to create machine language instructions that represents by a the numerical value of multiplying a number represented by 3 times the sum of numbers represented by 0 plus d and dividing that result by a number represented by e WHEWH But that s not even close to the true level of detail A program in Fortran is organized like a typical story It has a beginning a middle and an end STORY Once upon a time there was a little girl named Goldilocks and there were three bears who lived nearby in the Woods Goldilocks ran from the house and never went into the Woods again and what s more she and the bears lived happily ever after FORTRAN PROGRAM Declaration section PROGRAM classroomexample Any comment may be preceded by a IMPLICIT NONE INTEGER X declares an integer variable called x Execution section WRITE quotProgram startquot WRITE quotEnter an integerquot READ X Reads the keyedin value and call it x WRITE You entered WRITE X Writes the variable x to the console Window Etc etc Termination Section STOP END PROGRAM classroomeXample COMPLETE PROGRAM PROGRAM classroomeXample Here an entire program IMPLICIT NONE INTEGER X declares an integer variable called x WRITE quotProgram startzquot WRITE quotEnter an integerquot READ X Reads the keyedin value and calls it x WRITE You entered WRITE X Writes the variable x to the console Window STOP END PROGRAM classroomeXample All FORTRAN programs must be stored in files ending in the extension f95 for example Pgmlf95 In order to use FORTRAN code it must first be compiled into object code or into an executable In order to compile NAGWARE must be added to the terminal window environment as follows eos add nagf95 Then the file can be compiled into an executable file as follows eos f95 o Pgmlexe Pgmlf95 This will create a file called quotPgmlexequot that will execute when its name is typed in the terminal window ltlN CLASS DEMONSTRATIONgt Constants and Variables Constants De ned before program execution Variables May change value during the execution of a program Variable and constant names a Must have unique names b Names cannot be longer than 31 characters c Names cannot begin with a number d Names can only contain letters digits and the underscore e Names are NOT case sensitive so abc Abc ch ABc abC AbC aBC ABC are all considered to be the same Good time XValue SticklnThe Mud32 Bad 2timer abcdefghijklmnopqrstuvwxyz12345 6 lhaveauestion FORTRAN has 5 variable types INTEGER REAL COMPLEX LOGICAL CHARACTER Examples of INTEGER constants 23 32 55 REAL constants 314 314 314 0314E1 314E02 COMPLEX constants not to worry LOGICAL constants TRUE FALSE CHARACTER constants Robert Rodman 23 skidoo Declaration CHARACTER namelen13 Assignment Statements and Arithmetic Calculations variablename expression expression A totally parenthesized algebraic expression consisting of variable and constants and the following operators a Addition b Subtraction c Multiplication d Division e Exponentiation Good xaquotlt bc23 yaquotlt x discbquotlt gt 240quot aquot c Bad xabc yax discb240ac PARENTHESIZE PARENTHESIZE PARENTHESIZE MIXING TYPES DON T DO IT USE INTEGER TYPES WHEN ALL RESULTS ARE GOING TO BE INTEGERS OTHERWISE USE REAL TYPES INTEGERij REALXy GOOD ij1 ii1 iij ji4 ij3 xy15 x314y05 BAD ix ji2 ijx jij 5 Debugging Syntax errors are errors in form Eg INTEGER in WRITE quotProgram start Runtime errors occur when an illegal operation is attempted during the execution of the program Eg x00 yZX Logical errors are errors in the formulation of the program All DEMOs work 3242009 Lab 8 Modules 1 Sharing Data Remember when you were little and your mother encouraged you to share your toys Sharing we learn at ayoung age is important Your mother was right Fortran is very much about sharing You share the compiler and you share the library of intrinsic functions If you need the cosine of some angle you don t have to write a Taylor series subroutine to compute it You take advantage of the fact that someone once did and you get to use it This sharing is public Everyone has access to it But sharing can be private too and in the most extreme case private to one person you the programmer Suppose you have private data perhaps a cryptographic key and you have lots of programs that require access to that data You can create a personal library that contains that data and make that library available to every one of your programs Such a collection of data is shelved in a MODULE Suppose your secret 8digit key is 011235813 and you don t want it showing up in every program that uses it You put it in a module MODULE key IMPLICIT NONE SAVE INTEGER DIMENSION8mykey0ll2358l3 END MODULE key We can compile this as it stands Suppose it is stored in Modf95 Then 95 c Modf95 This produces Modo DEMO IN CLASS The module is used with what else a USE statement PROGRAM testmodule USE key key is the name of the module IMPLICIT NONE INTEGER i WRITE10 mykeyi il8 10 FORMAT10X 813 END PROGRAM testmodule I store this in ModDriver 95 CAUTION If I just do this 95 ModDriver 95 it crashes DEMO l have to give it a reference to the module this way 95 ModDriver 95 Modo Now when I execute aoutl see the results DEMO Or 95 ModDriver 95 o ModDriverexe Modo DEMO Let s add a subroutine and a function to the driver program and show how the data can be shared among all these program units FUNCTION addup USE key IMPLICIT NONE INTEGER addupi addup0 DO i18 addupaddup mykeyi END DO END FUNCTION addup And we add this to our program with one additional WRITE stmt PROGRAM testm0dule USE key IMPLICIT NONE INTEGER i addup WRITE 10 m ke ii18 10 FORMAT10X 813 END PROGRAM testm0dule licicz cz FUNCTION addup USE key IMPLICIT NONE INTEGER addupi addup0 DO i18 addupaddup mykeyi END DO END FUNCTION addup And we compile this Whole thing P95 ModDriverFuncf95 o ModDriverFuncexe ModTesto DEMO And how about a subroutine that prints the key backwards SUBROUTINE reverse USE key IMPLICIT NONE INTEGER DIMENSION8 rkey INTEGER 1 DO i18 rkey9imykeyi END DO WRITE11 rkeyi i18 11 FORMAT10X 813 END SUBROUTINE reverse And put this all together with a call to the subroutine PROGRAM testm0dule USE key IMPLICIT NONE INTEGERi addup WRITE10 mykeyi i18 WRITE 39Sum 39 addup 10 FORMAT10X 813 END PROGRAM testm0dule mmvmmmm FUNCTION addup USE key IMPLICIT NONE INTEGER addupi addup0 DO i18 addupaddup mykeyi END DO END FUNCTION addup mmmmmmmm SUBROUTINE reverse USE key IMPLICIT NONE INTEGER DIMENSION8 rkey INTEGER i DO i18 rkey9imykeyi END DO WRITE11 rkeyi i18 11 FORMAT10X 813 END SUBROUTINE reverse We compile and run this f95 ModDriverFuncSubrf95 o ModDriverFuncSubrexe Modo 2 Module Procedures In addition to data modules may also contain complete subroutines and functions known as module procedures These procedures are compiled as part of the module and made available to a program unit by including the USE statement containing the module name Module procedures must come after all data declarations in the module and must be proceeded by a CONTAINS statement As used above function addiup and subroutine reverse are themselves external procedures External procedures do not provide the compiler with an explicit interface additional information that the compiler can use to cross check how the variables in the calling sequences are used To achieve explicit interfacing we can and should place subroutines in a module compile the module and USE it in the main program Let s package our two little subroutines into the data module so we have a very simple little driver program It goes like this MODULE keyplus IMPLICIT NONE SAVE INTEGER DIMENSION8mykey011235813 CONTAINS FUNCTION addup IMPLICIT NONE INTEGER addupi addup0 DO i18 addupaddup mykeyi END DO END FUNCTION addup SUBROUTINE reverse IMPLICIT NONE INTEGER DIMENSION8 rkey INTEGER i DO i18 rkey9imykeyi END DO WRITE11 rkeyi i18 11 FORMAT10X 813 END SUBROUTINE reverse END MODULE keyplus And compile P95 c Modplusf95 DEMO The Driver is now simpler but does the same thing PROGRAM testm0dule USE keyplus IMPLICIT NONE INTEGERzzi not needed produces dup declar error WRITE10 mykeyi i18 WRITE 39Sum 39 addup CALL reverse 10 FORMAT10X 813 END PROGRAM testm0dule f95 M0dDriverplusf95 0 M0dDriverplusexe M0dplus0 At this point any program could use the data the subroutine and the function just as in the program Are there ever situations Where you cannot use external procedures and must use a module Consider the following Ordinarily we can place our functions and subroutines in a module compile the module and USE it This provides an explicit interface We can also just include them as external procedures which how we first used subroutines and functions FUNCTION Xa b n IMPLICIT NONE INTEGER 11 REAL Xn n an nbn n xab END FUNCTION X This is a matriX function that computes the sum of two matrices The driving program uses allocatable arrays as it should FUNCTION Xa b n IMPLICIT NONE INTEGER 11 REAL Xn n an nbn n xab END FUNCTION PROGRAM test IMPLICIT NONE INTEGER i REALALLOCATABLE array REALALLOCATABLE arrayl REALALLOCATABLE array2 i 5 ALLOCATEarrayii ALLOCATEarraylii ALLOCATEarray2ii CALL RANDOMNUMBERarray 1 CALL RANDOMNUMBERarrayZ array Xarraylarray2i END PROGRAM Here the function x is an external procedure but look at What happens when I go to compile it There is confusion over the status of X DEMO Implicit type for X error I95 IBfuncWithErrorf95 But when I put the function in a module everything is cool MODULE holdfunction IMPLICIT NONE CONTAINS FUNCTION Xa b n IMPLICIT NONE INTEGER 11 REAL Xn n an nbn n xab END FUNCTION END MODULE holdfunction F95 c IBfuncInModulef95 produces IBfuncInModuleo DEMO Add the USE statement PROGRAM test IMPLICIT NONE INTEGER i REALALLOCATABLE array REALALLOCATABLE arrayl REALALLOCATABLE array2 i 5 ALLOCATEarrayii ALLOCATEarraylii ALLOCATEarray2ii CALL RANDOMNUMBERarrayl CALL RANDOMNUMBERarray2 array Xarraylarray2i END PROGRAM P95 IBdrivefuncInModulef95 IBfuncInModuleo DEMO Now it compiles With allocatable arrays it s necessary to have the explicit interface provided by the modules And now we can complicate things a little to get output PROGRAM test USE holdfunction IMPLICIT NONE INTEGER i REALALLOCATABLE array REALALLOCATABLE array1 REALALLOCATABLE array2 i 5 ALLOCATEarrayii ALLOCATEarray1ii ALLOCATEarray2ii CALL RANDOMNUMBERarray1 CALL RANDOMNUMBERarray2 arra X arra 1array2i END PROGRAM P95 IBdrivefuncInModuleWithOutputf95 IBfuncInModuleo This compiles We run aout to see the matrix addition Flow of control What to do next 1 Take the next instruction 2 Take an instruction other than the next instruction Computing is truly that simple ignoring parallel processing and distributed processing Often we want to repeat the same sequence of instructions with small changes We need small changes to avoid insanity which among humans is defined quotInsanity is doing the same thing over and over and expecting different results Benjamin Franklin For computers insanity is an infinite loop which must be avoided Loops 1 DO Loops The idea is we have a sequence of things we want to do repeatedly and we want to do them until something tells us to stop In math 21 1 to 100 1 repeatedly adds the integers l23 and stops when 100 is reached DO Loop DO bunch of instructions IF logicaleXpression EXIT bunch of instructions END DO The bunches of instructions execute repeatedly until the logical eXpression is true and then control resumes below the END DO Eg sum0 i1 DO sumsumi IF i 100 EXIT iil sum5050 Or this sum0 i1 DO sumsumi ii1 IF i 101 EXIT END DO Or this sum0 i1 DO IF i 101 EXIT sumsumi ii1 END DO But not this sum0 i1 DO IF i 101 EXIT sumsumi END DO And not this sum0 i1 DO sumsumi ii1 END DO Counting DO Loops When you know in advance how many times you want to repeat your do this sum0 DO i1100 sumsumi END DO sum5050 The value of i may be unreliable out side the DO END DO Each time through i is bumped up by l but if you wanted to add the odd integers less than 100 you could do this sum0 DO i11002 sumsumi END DO sum2500 The increment is 2 so il35 If you want to be a rocket scientist you may want to count backwards That s fine sum0 DO i100ll sumsumi END DO sum5050 But beware sum0 DO i100 l sumsum i END DO If you omit the increment it defaults to 1 Here we ve created an infinite loop that will soon crash Most important I NEVER MODIFY AN INDEX WITHIN THE DO LOOP 2 THE VALUE OF A DO LOOP INDEX IS VALID ONLY WITHIN THE DO LOOP Bells and Whistles CYCLE statement This causes control to skip the remaining instructions and return to the top of the loop Suppose you want to add the odd numbers less than 100 but you want to omit 69 because someone once said it was a bad word sum0 DO i11002 IF i 69 CYCLE sumsumi END DO sum243l EXIT statement This causes any DO loop to terminate based on some condition even a counting loop Suppose you want to add up numbers through 100 but only while the sum is less than the value in the variable max sum0 DO i1100 IF sum gt maX EXIT sumsumi END DO Nested loops and giving names to loops Sometimes we have need to have DO loops Within DO loops Here is an excerpt of a piece of code for solving Sudoku puzzles This is a bit hard to read DO ifdeltafix0 EXIT fixcountlast fixcount fixcount 0 DO i191 DOj191 DO k191 IF gn dijk 0 THEN countcount1 kmaybe k END IF END DO IF count1 THEN CALL removecolijkmaybeg d CALL removerowijkmaybegn39d CALL removesquareijkmaybeg d fixc ountfixcount 1 ELSE IF count0 THEN kosher FALSE END IF count 0 END DO END DO deltafix xcount fixcountlast END DO We can make it easier to follow by providing names for each DO loop linking the various DOs with its matching END DOs L1 DO ifdeltafix0 EXIT fixcountlast fixcount fixcount 0 L2 DO i191 L3 DOj191 L4 DO k191 IF gn dijk 0 THEN countcount1 kmaybe k END IF END DO L4 IF count1 THEN CALL removecolijkmaybeg d CALL removerowijkmaybegn39d CALL removesquareijkmaybeg d fixc ountfixcount 1 ELSE IF count0 THEN kosher FALSE END IF count 0 END DO L3 END DO L2 deltafix xcount fixcountlast END DO L1 Finally any of the parameters in the DO loop may be program variables integers The general form is DO indexstart end increment Where increment defaults to 1 if missing E g Integer abci Do iabc etc In fact you can put an eXpression into a DO loop Do jabacdincr How does Fortran know when to quit a loop If it s a rising loop then quit when indexgtend If it s a falling loop then quit when indexltend But if the parameters are variables their value is determined at runtime and the quitting conditions are different Here s how clever Fortran is First rewrite the quitting conditions Rising index end gt 0 positive increment Falling index end lt 0 negative increment If we multiply the Falling condition by l we get the Rising condition If indeX end lt 0 then lindeX end gt 0 right So whenever the value of increment is negative multiply indeX end by l The easiest way to do that is to compute increment increment where l means absolute value When increment is positive the value is 1 When its negative the value is 1 So the ending condition for both rising and falling loops is merely increment incrementgtltindeX end gt 0 and the values can be determined at runtime and needn t be known in advance Lab 7 Procedures Writing a computer program is like building a house As the builder you have the big picture So many bedrooms bathrooms a media room a kitchen a family room and so on You know the layout and the square footage But when you actually build the house there are a lot of little jobs like wiring and plumbing that are pretty much the same from house to house These are the jobs of the subcontractors Subcontractors do the same thing over and over again In programming we have a similar situation There are computations that are done repeatedly with just a little variation You d like to isolate them debug them separately and keep them for reuse whenever needed These are the subcontractors of building a program In general these subcontractors or subprograms are called procedures We are concerned with two kinds of procedures subroutines and functions 1 Subroutines Plumber do more or less the same thing every time Lay pipe attach to sinks faucets commodes and the like Each plumbing job is essentially the same the differences are location and number of things to be plumbed So the plumber gets input your house plan Based on the input he does same old same old and produces output a properly plumbed house A subroutine is the same kind of thing It performs a certain basic task solves a quadratic equation say but each output will depend on the particular input A subroutine may be compiled separately debugged separately and then used Whenever needed The variables in a subroutine are local to the subroutine and only have validity within the subroutine Here is the general form of a subroutine definition SUBROUTINE subroutinename argumentist IMPLICIT NONE Decaration Section Execution Section ETURN END SUBROUTINE subroutinename Specifically SUBROUTINE quad abcr1r2i1i2 ISolve aXA2bxc0 IMPLICIT NONE REAL INTENTINabc REAL IN TEN T0UT r1r2i1 i2 REALdisc i10 i20 discb 240 aquot c IF discgt0 THEN r1 bSQRTdisc20a r2 bSQRTdisc20a ELSE IF disc0 THEN r1b20a r2r1 ELSE r1 b20a r2r1 i1SQRTABSdis c2 0 a i2SQRTABSdis c2 0 a END IF RETURN END SUBROUTINE quad The name of the subroutine is arbitrary just like the name of the program but it should be named something meaningful The arguments in the argument list are called dummy variables They are like the x in fX2x3 The x is a placeholder and could be any letter fz2z3 without altering the definition or anything really f 2gtlt 3 The values are instantiated wow big word or given value when the subroutine is invoked as we ll see Subroutines are independent program units This means that they can be compiled separately from the main program and that variable names within subroutines are only valid within the subroutine and they cannot be referenced outside of the subroutine In the declaration section each of the arguments in the argument list and variables that will be used locally in the subroutine must be declared For arguments in the argument list the INTENT attribute is used to protect variables from being used improperly and being changed when they should not be changed There are 3 different INTENT attributes that can be used REALINTENTIN Used when arguments come from the calling program as input only They cannot must not be changed in the subroutine REALINTENTOUT Used when arguments are only to be returned from the subroutine to the calling program Their value is set in the subroutine REALINTENTINOUT Used when arguments come from the calling program can be used as both input and output They may be modified within the subroutine and returned to the calling program Here is a bit more with declarations SUBROUTINE quad abcr1r2i1i2 ISolve aXA2bxc0 IMPLICIT NONE REAL INTENTINa b c REAL INTENTOUTr1r2i1i2 REALzzdisc i10 i20 discb 240 aquot c IF discgt0 THEN r1 bSQRTdisc20a r2 bSQRTdisc20a ELSE IF disc0 THEN r1b20a r2r1 ELSE r1 b20a r2r1 i1SQRTABSdisc20a i2SQRTABSdisc20a END IF RETURN END SUBROUTINE quad And here is the Whole shebang SUBROUTINE quad abcr1r2i1i2 ISolve axA2bxc0 IMPLICIT NONE REAL INTENTINa b c REAL INTENTOUTr1r2i1i2 REALzzdisc i10 i20 discb2 40ac IF discgt0 THEN r1bSQRTdisc20a r2bSQRTdisc20a ELSE IF disc0 THEN r1b20a r2r1 ELSE r1b20a r2r1 i1SQRTABSdisc20a i2SQRTABSdisc20a END IF RETURN END SUBROUTINE quad Any executable program unit can call a subroutine which looks like this CALL subroutinename argumentlist Specifically PROGRAM testquad IMPLICIT NONE REALa0 a1 a2 rootl r00t2 irootl ir00t2 lsolve a2xA2alxa00 lroot and iroot are real and imaginary parts WRITE 39ENTER REALS A B AND C for AXA2BXC039 READ a2 a1 a0 CALL quada2 a1 a0 rootl r00t2 irootl ir00t2 WRITE100 rootl r00t2 irootl ir00t2 100 FORMAT2X39real r00ts 392F104 6X 39imag r00ts 392F104 END PROGRAM testquad Where the order and type of the actual arguments in the argument list must match the order and type of the dummy arguments declared in the subroutine the names of the arguments do not have to match though CALL quada2 a1 a0 rootl r00t2ir00t1ir00t2 SUBROUTINE quad a b c r1 r2 i1 i2 Here is the Whole thing PROGRAM testquad IMPLICIT NONE REALa0 a1 a2 r00t1 r00t2 ir00t1 ir00t2 Isolve a2xA2a1xa00 Iroot and iroot are real and imaginary parts WRITE 39ENTER REALS A B AND C for Axquot2BxC039 READ a2 a1 a0 CALL quada2 a1 a0 r00t1 r00t2 ir00t1 ir00t2 WRITE100 rootl r00t2 ir00t1 ir00t2 100 FORMAT2X39real r00ts 392F104 6x 39imag r00ts 392F104 END PROGRAM testquad SUBROUTINE quad abcr1r2i1i2 ISolve axA2bxc0 IMPLICIT NONE REAL INTENTINa b c REAL INTENTOUTr1r2i1i2 REALzzdisc i10 i20 discb2 40ac IF discgt0 THEN r1bSQRTdisc20a r2bSQRTdisc20a ELSE IF disc0 THEN r1b20a r2r1 ELSE r1b20a r2r1 i1SQRTABSdisc20a i2SQRTABSdisc20a END IF RETURN END SUBROUTINE quad RUN DEMO quadsolversubroutinef95 2 Functions The second type of procedure is the FUNCTION This type of procedure has a result of a single number logical value character string or array There are two types of functions Intrinsic and User Defined You ve already used intrinsic functions SQRT is an example It is used exactly as if it were a variable Where its value is the square root of its argument E g bSQRTa WRITE SQRTXy User Defined functions are functions that the user writes The general form of a user defined FORTRAN function is as follows FUNCTION name argumentlist IMPLICIT NONE Declaration Section Execution Section name eXpression RETURN END FUNCTION name Specifically a function to compute n factorial nlgtlt2gtlt gtltn FUNCTION facto rialn IMPLICIT NONE INTEGER INTENTIN n INTEGER factoriali factorial1 DO i1n factorialfact0riali END DO RETURN END FUNCTION factorial In the body at least one statement assigns a value to the function name just as if it were a variable FUNCTION factorialn IMPLICIT NONE INTEGER INTENTINn INTEGER factorial i factorial1 DO i1n factorialfactoriali END DO RETURN END FUNCTION factorial The program that uses the function uses it as if it were a variable PROGRAM computefactorial IMPLICIT NONE INTEGER n factorial WRITE39Enter number for factorial39 READ n WRITEn 39 39 factorialn END PROGRAM computefactorial In toto FUNCTION factorialn IMPLICIT NONE INTEGER INTENTINn INTEGER factoriali factorial1 DO i1n factorialfactoriali END DO RETURN END FUNCTION factorial Hmmmmmmm PROGRAM computefactorial IMPLICIT NONE INTEGERzzn factorial WRITE39Enter number for factorial39 READn WRITEn39 39fact0rialn END PROGRAM computefactorial DEMO 2008FactorialANDFibonaccifactnonrecufuncf95 Finally subroutines and functions may be de ned above or below the main program Files and File Processing But think of it as Songs and Music Processing Nearly everybody is familiar with that Historically songs have been stored in many formats A magnetized Wire grooves in vinyl various tape formats cassettes 8track and nowadays in various digital formats Music is data A album is a file Each song is a record So Radiohead s album In Rainbows is like a file each individual song such as Nude is like a record A file is a collection of records with some common theme such as songs by a certain group or data from a certain experiment or transactions from a certain bank and so on Files are useful because they store large amounts of data that can be easily moved around and manipulated An album is far more convenient than a bunch of individual songs let alone a bunch of individual notes of a song 1 Opening Files When you go to play or input music let s say a CD you must first open the CD case Likewise when you need a file of data for input into a computer program you must open that file with a Fortran command Then you choose a device to play it on maybe the player in your home or in your car or maybe even an oldfashioned portable player This is the input unit Same with the computer You may input through the keyboard from memory or from your hard drive from a key and so on You issue a Fortran command to identify the input unit Let s look at a little Fortran Here is the open statement or the start of one OPEN UNIT12 FILE In Rainbowsmus The 12 is the code for the input device or CD player to continue the musical metaphor It becomes associated with the file or songs of interest Your lab instructor will give you the proper unit numbers It will correspond to some source of data The alphanumeric that follows the key word FILE is the computer name of the file of data you are interested in and is like the name of the album The next keyword muddies our musical metaphor but if we replace the CD by cassette tape a what you can imagine that you might want to a listen to the album b make your own album by singing a bunch of songs and recording over what s on the tape or c make your own album by singing a bunch of songs and recording onto a fresh tape STATUS OLD STATUS REPLACE STATUS NEW achieve these goals The OLD says this is an existing le and is not to be overwritten REPLACE says there may be older data that may be overwritten And NEW says there is a new file to be created OPEN UNIT12 FILE In Rainbowsmus STATUS OLD You can announce your intentions as to whether you are going to listen or record read or write with the ACTION keyword ACTION READ ACTION WRITE ACTION READWRITE where READ means listen only or data input only WRITE means I m gonna sing that is output only And READWRITE means I may listen to one or two songs and then record my own music or viceversa OPEN UNIT12 FILE In Rainbowsmus STATUS OLD ACTION READ Usually when your musical system fails you are rewarded with silence or worse you sing your heart out and nothing gets recorded With computer data files you can provide an error flag that will be set to certain values depending on how the computer is feeling toward your file This flag may then be examined to see what s up The keyword here is IOSTAT inputoutput status and you choose your own variable name to hold the info It looks like IOSTAT avariabley0ugive If the open statement is successful a zero will be returned in the integer variable avariableyougive If not successful a positive number corresponding to a system error message will be returned in the variable Continuing our example INTEGER ioflag OPEN UNIT12 FILE In Rainbowsmus STATUS OLD ACTION READ IOSTATi0 ag And that s all there is to it Fairly straightforward wouldn t you say After the OPEN you can write some code like IF io ag 0 THEN WRITE Error reading file STOP END IF Here is an example of opening a file that is to be created OPEN UNIT 13 FILE quotnewbieda quot STATUSquotNEWquot ACTION quotWRITEquot IOSTAT ierror The STATUSquotNEWquot specifies that the file must be created However if the file already exists there will be an error message number in the ierror variable stating that the le already exists If the programmer doesn39t mind replacing a le with a new file then the programmer can use the STATUS quotREPLACEquot statement There is one last statement that has not been explained the STATUS quotSCRATCHquot statement With this statement no file name can be speci ed This is simply a temporary scratch file that can hold information during the execution of the program Once the program has terminated the scratch file no longer exists The statement is simplicity itself OPEN UNIT 13 STATUSquotSCRATCH Oh and while we re at another one last thing you can parameterize the unit number INTEGER PARAMETER scr 13 io unit for scratch file OPEN UNIT scr STATUSquotSCRATCH and that gives you some exibility with the unit numbers 2 Closing Files The CLOSE statement closes a file and releases the unit number associated with it back to the computer Once a file is closed the unit number can be reused by another file When the program is finished with the file the CLOSE statement must be used to close the file and return the unit number to the operating system The syntax for closing a file is as follows CLOSE13 Now that is easy 3 File Reading and Writing Once a file has been associated with a unit number Via the OPEN statement the unit number can be used to read from the file or write to the file The unit number is just a short cut way to refer to the file This can be done using the same READ and WRITE statements we have been using already For example OPEN UNIT 12 FILE quotinputda quot STATUS quotOLDquot IOSTAT ierr0r READ12 x y z 12 is the unit number of the le This READ statement will read X y and z from the first line of the input le Here s another example OPEN UNIT 13 FILE quot0utputdatquot STATUS quotREPLACEquot IOSTAT ierr0r 100 FORMAT 39 X 39 F10239 Y 39 F102 39 z 39 F102 WRITE 13100 x y z This will write the values of X y and z to the file outputdat in the format specified by the 100 FORMAT statement 4 There are two additional commands that are very useful When processing files The music analogy is apropos here Often you want to hear your music starting with the first song You can set the track to l on a CD or DVD or rewind a tape to the beginning or just touch a button on your digital play which might well be called rewind REWIND This command is used to rewind or restart the file at its beginning This is useful when you need to reuse the values in the le Here it is REWIND12 Whatever file is associated with unit number 12 is such that when you READ or WRITE you ll be at the start of the file Sometimes you want to here a song or two over again without going back to the beginning of the album All music players allow you to go back one song or more formally to backspace You can do the same thing in a data file BACKSPACE This command is used to back up a single record in a le If you wanted to back up three records you would use the command three times The syntaX for this command is as follows BACKSPACE17 Back up one song oops record in the le associated with unit 17 Formatting InputOutput Unless we re printing a few numbers for our own use it is almost always necessary to pretty print Pretty print means presenting the output in a structured way so that it is easier for the user to comprehend Presentation is the major name of the game in web programing but it is important in any programing environment including Fortran What are some of the factors that govern What a screen looks like A screen is made up of lines and characters Within a line It is not unlike a ruled sheet of paper or of quadrilled paper with one square per character so a line has somewhat more than 100 squares Indeed output can be planned using something like o What goes on each line including blank or skipped lines o What goes in each square of a line including blanks or spaces 0 When does a new screen page begin Fortran has a tool called a Format Statement that permits the programer to design screen output But let s think this through What is output 1 Words or sentences describing things Eg Please enter your height and weight or Height or Input out of range or pi3 14159265 2 The value of a Fortran variable THAT S IT What else is there 1 is easy Just put around any literal output 2 has more detail because of the different variable types In all cases we have to determine the Line the Field which squares within the line and whether the output is left or right Justified This is not unlike what you do when you type a document In the following we assume we have already determined a line and a place within that line to begin the field a INTEGER The only question is the length of the field The integer will be right justi ed in the field The field must be of sufficient length to display the entire integer including the sign without it butting up against other output b REAL Just as anywhere in mathematics there are several ways to display a real number In all of them the length of the field must be chosen and it must accommodate all of the characters used to eXpress the number without butting up against its neighbors i Decimal notation digits digits eg 4319 ii Exponential notation 0 digits E two digits eg 04319E02 iii Scientific notation digit digits E two digits eg 4319E01 c CHARACTER A character variable has its own inherent length that is determined when the variable is declared The field must be sufficiently large to contain the individual characters If it is larger the placement is right justified THAT S REALLY ALL THERE IS TO IT BUT AS SO OFTEN IN LIFE THE DEVIL IS IN THE DETAILS We communicate our output design to the Fortran compiler Via a FORMAT statement This is almost a programing language unto itself The FORMAT statement is labeled with a number and referenced in a WRITE statement 100 FORMATinfo goes here WRITE100 ltlist of variables or thing in quote marksgt The information in the FORMAT statement may be folded into the WRITE statement but we ll stick with a separate FORMAT statement for lecture purposes WRITE info goes here ltlist of variables etcgt Output begins Wherever the curser is on your screen The FORMAT statement uses 9 descriptors together with Whole numbers n and commas Descriptor The gives anew line The X descriptor looks like nX and moves the cursor over 11 spaces eg 6X skips 6 spaces The T descriptor means ta so Tc moves the cursor to column c eg T22 means start the next output in column 22 The I descriptor is for integers so In reserves 11 spaces for an integer eg l6 reserves 6 spaces for the integer The F descriptor is for reals so Fmn reserves m spaces for the entire number with n of those spaces after the decimal point eg F104 defines a total field Width of 10 with 4 digits to follow the decimal point The E descriptor is for reals so Emn is like Fmn in that it reserves m spaces for the entire number with n of those spaces after the decimal point The output is always of the form 0dddEidd eg E205 defines a field width of 20 spaces with 5 spaces after the decimal point Note the field must be Wide enough to accommodate all the character including a possible negative sign the leading 0 the decimal point all the digits the E and the sign of the eXponent The ES descriptor is also for reals and ESmn is identical to Emn except the output looks like ddd dEidd Same comments as with the E descriptor The A descriptor is for outputting character types so that An reserves 11 spaces for the character string If n is larger than the number of characters they are right justified A alone will exactly accommodate the character variable The L descriptor is for logical output We won t worry about it now So that s not too bad One other thing anytime a descriptor is preceded by a number ie a repeat factor it means repeat so 416 means 4 fields of length 6 for integers occupying a total of 24 spaces Suppose we want to print the following to the screen The total number of groceries is and the total cost is Suppose the integer variable groceries holds the number of groceries the real variable cost holds the total cost of the groceries and the text is just included on the WRITE line as follows 50 FORMATA12AF52A WRITE50 quotThe total number of groceries is quot groceries amp amp quot and the cost is quot costquotquot You could also do it this way just for the record WRITE A12AF52A where stand for all the stuff after WRITE50 You ll probably have to study the textbook and the lab manual for all the details that you may need to complete your assignments A few more examples 110 FORMATI43XF51 Eg 29 239 111 FORMATI4T10F51 Eg 526451 The 6 is in column 10 112 FORMAT4I4T203F51 Eg 12345678823113423119 113 FORMATI453XF51 Eg 1212341234123412341234 114 FORMATI43XF51 the slash skips t0 the next line Eg 12 1234 115 FORMATI43xF513IS 3 slashes skips 3 lines down Eg 12 1234 123456 And one last thing gasp ADVANCEquotNOquot Ordinarily 100 FORMATA WRITE100 quotEnter your agequot Output Enter your age JCursor waits here But you could do this WRITE100ADVANCE NO quotEnter your age quot Output Enter your age JCursor waits here PROGRAM fonnatexample IMPLICIT NONE INTEGER age declares an integer variable called age 100 FORMATA 200 FORMATA2XI3 WRITE100 quotEnter your age Note the cursorquot Read age WRITE200 quotTwice your age is quotage2 WRITE100ADVANCEquotNOquot quotNowenter your age again No ampAdvance casequot READ WRITE200 quotThe square ofyour age isquot age2 STOP END PROGRAM formatexample J eos ncsu educoursescsccscllZlecOOlwww Do iOn X reali yl X3044 y2 X l 2X y3 Xl9 4X End Do Lab 6 Arrays Information often comes to us in the form of a list or a table of values such as a list of square roots of integers l0000 l4l42 l732l 20000 22361 etc Or the multiplication tables 5 6 10 12 These data structures are useful for computing with large amounts of data such as What you might find in payroll records of a large company or lab research into weather conditions We call a list a onedimensional array A table as we usually understand the word is a twodimensional array A sudoku puzzle is an example Multidimensional gt2 arrays are conceivable so for plotting values in 3space you might require a threedimensional array and so on In practice one and two dimensional arrays suit a large percentage of needs When you have a list you can refer to the elements in the list by their position in the list or their index Thus the square root of 5 is fifth on the list of square roots and if we called the list Squareroot we might write Squareroot52236l Same drill for the table I can describe the entry in the third row fourth column as Mult34 and in my multiplication table I would have Mult3412 If the value 1711 occurred when x2 y3 z5 in threespace then we might have Threespace235l 7 11 All of these structures are arrays and as long as the elements in the arrays are of the same type REAL INTEGER they can be dealt with in Fortran In Fortran arrays are treated as if they were just another data type like REAL or CHARACTER but the word DIMENSION is used in the declaration and that word is preceded by the data type of the elements that the array is to contain REAL DIMENSION But that s not all In the case of a list or a onedimensional array we must declare its size and we must give it a name just as we do in any variable declaration REAL DIMENSION100 squarer00t This gives us a list of size 100 indexed from 1 to 100 so that squareroot23 refers to the 23rd element in the list and so on To be eXible Fortran also permits the declaration to look like REAL squarer00t100 Or for a list of integer types of size 50 we would declare INTEGER anotherlist50 If we want to refer to a specific element of an array in a program let s say to double it you do this anotherlist1 2an0therlist1 and to double the entire list of integers use a loop DO i150 anotherlisti 2an0therlisti END DO What happens if I inadvertently do this You re quotamp DO i1100 anotherlisti 2an0therlisti END DO The first element in a FORTRAN array is ordinarily subscript l but it s possible to have any starting and ending subscript by doing this REAL startwithzer0099 which de nes an array of size 100 indexed from 0 to 99 Even negative indices are permitted INTEGER angles1515 defines an array of length indexed from 15 to 15 Using Elements of Arrays Individual elements in arrays properly referred to by an index that may be a constant or a variable are used just like any variable You can write them WRITE testS Read them READ testS Set their value test5Xy Use them in a formula to set other values ztest5test6 Or work with all or part of the array usually in a DO loop sum0 DO i16 sumsum testi END D0 will total the elements from testl through test6 Useful shortcuts and flexibility Arrays may be initialized if they re not too long Otherwise initial values in our system are 0 INTEGER array14 3456 initializes arrayl to 3 array2 to 4 and so on You can also work with whole arrays Just make sure they re the same size Starting with REAL vector1100 vector2100 vector3100 DO i1100 vector3ivector1 ivecto r2 i END DO This will put the sum of the two vectors into a third but So will this vector3vector1vector2 But that s not all You can work with pieces of arrays called array subsets Just be careful not to miX apples and oranges that is array subsets of different sizes vect0r3150 vect0r1150vect0r251100 will set the first 50 elements of vector 3 to the sum of the first 50 elements of vector 1 plus the last 50 elements of vector 2 Now that s cool What does this do vect0r32650 vect0r1125vect0r276100 Or this vect0r3125 2vect0r376100 Or if we have REAL vect0r425 what about this vect0r4 vect0r1125 vect0r22650 Clearly I hope the constants I m illustrating with could be replaced by variables indices but you must always worry about things matching up vect0r3ijvect0r1kmvect0r2n p will work fine as long as ji mk and pn are all equal TwoDimensional amp MultiDimensional Arrays Twodimensional and multidimensional arrays are declared similarly to single dimension arrays Single dimensional arrays only have 1 subscript while a twodimensional array has 2 subscripts and multidimensional arrays have up to 7 subscripts A simple twodimensional array is declared as follows INTEGER table1212 This defines a 12 by 12 table suitable perhaps for a multiplication table where tableij contains ij for values of i and j between 1 and 12 Here s code to establish the value of such a table DOi1J2 DOj1J2 mmamnj ENDDO ENDDO table is a square array one with equal numbers of rows and columns but of course one can have arrays of any size INTEGER table212 would have 2 rows and 12 columns 12345678 9101112 1 2 gtlltgtllt gtllt The indexing as before runs from 1 on up but all the other possibilities are available to you INTEGER table011011 is still a 12 by 12 table but indexing runs from 0 to 11 As always elements in multidimensional arrays may be referred to just as ordinary variables are used You can write them WRITE table56 Read them READ table612 Set their value table11xy Use them in a formula to set other values ztable11table22 Or work with all or part of the array usually in a DO loop sumfifthcolumn 0 DO i112 sumfifthcolum sumfifthcolumn tablei5 END DO sumuppertriangle 0 DO i112 DO ji12 sumuppertriangle sumuppertriangle tableij END DO END DO This is table11 table 112 table 22 table 23 table 212 table1212 or adds the red asterisks gt1lt gt1lt gt9gtegtegtegtegtegtegtegtegtegteee gt9gtegtegtegtegtegtegtegtegtee ee gt9gtegtegtegtegtegtegtegte gt9gtegtegtegtegtegtegte gt9gtegtegtegtegtegte eeeeeeeeeeeeeeeeeeeeee Arrays may be initialized DO i112 DO j112 tableij0 END DO END DO Or with whole arrays table0 And even array subsets work though you must take care to keep everything the same size and respect dimensionality tablel6116 table 712712 sets the upperleft quadrant values to the lowerright quadrant value so tablell is set to table77 tablel2 is set to table 78 table 66 is set to table 1212 More shortcuts Intrinsic Functions with Arrays Many intrinsic built in functions for scalar arguments may be applied to whole arrays REAL DIMENSION10 x y READ Xi i110 y SQRTX will set vector y to the square root of ten values that are read into vector X The READ statement contains an implied D0 002 Some intrinsic functions are designed for arrays alone If you consider a twodimensional array to be a matrix then Fortran will do matrix multiplication quite simply REAL A1010 B1010 C1010 CAB And that s a complex computation In this example we had all matrices but one can take the dot product of two vectors and produce a scalar REAL A10 B10 REAL DotProduct DotProduct DOTPRODUCTAB Many intrinsic functions are located in Appendix B of the book These will become very useful in future assignments Allocatable Arrays Arrays can eat up a lot of memory REAL A10000 would force the operating system to allocate an in exible ten thousand words of memory even if you might only need so much on a rare occasion This type of array declaration is called static memory allocation Better is to use only the memory needed at the time called dynamic memory allocation This means that the array sizes are set during run time and not at the time of compilation These types of arrays have to be declared as follows 12 REAL ALLOCATABLE DIMENSION A or REAL ALLOCATABLE A Using this type of array usually means that the array size will be determined during execution whether by user input or by calculation When the size of the array is determined and the program needs the array then the array will be allocated as follows INTEGER status m n lset n to some value ALLOCATEAnSTATstatus IFstatus0 STOP STAT will return 0 to the integer variable status if the allocation is successful If not of course you must stop the program to avoid a runtime error In this case n is determined at execution time and only 11 slots are allocated Once the program is finished using the array the array should be deallocated so that the memory can be reused This is done as follows DEALLOCATEASTATstatus IFstatus0 STOP Multidimensional arrays work the same way and it may even be more critical REAL A10001000 would tie up a million words Better is REAL ALLOCATABLE A 13 and then at the proper moment during execution allocate only What you need set In and n to some values ALLOCATEAmnSTATstatus IFstatus0 STOP and later on deallocate DEALLOCATEASTATstatus IFstatus0 STOP SOFTWARE ENGINEERING is THE APPLICATION OF SCIENTIFICALLY TESTED TECHNIQUES AND METHODOLOGIES TO THE PROGRAMMING OF COMPUTERS DEVELOPING PROGRAMS IN FORTRAN WHAT YOU WILL BE DOING ALL SEMESTER IN YOUR LAB REQUIRES FIVE BASIC STEPS TOP DOIWVDESIGN 1 PROBLEM ANALYSIS AND SPECIFICATION 2 DATA ORGANIZATION AND ALGORITHM DESIGN 3 PROGRAM CODING 4 EXECUTION AND TESTING 5 PROGRAM MAINTENANCE LETS LOOK AT A SINIPLE EXANIPLE REAL PROBLEMS WILL BE MORE CONIPLEX TONY SOPRANO LOANS MONEY OUT AT THE RATE OF ONE PERCENT PER DAY COMPOUNDED VITO WANTS TO BORROW A FEW G39S AND HE NEEDS TO KNOW HOW MUCH HE WILL OWE TONY XDAYS LATER VITO ASKS A PROGRAMMER NAMED JIMMYTHEGEEK TO SOLVE THE PROBLEM ON A COMPUTER STEP 1 PROBLEM ANALYSIS AND SPECIFICATION INPUT INITIAL AMOUNT OF LOAN RATE OF INTEREST DURATION OF LOAN OUTPUT AMOUNT OWED STEP 2 DATA ORGANIZATION AND ALGORITHM DESIGN Data Organization We need to represent four quantities We give them meaningful names initialam0unt rate time amount0wed Algorithm Design large view 1 Get values for initialam0unt rate time 2 Compute amount0wed for any time 3 Output amount0wed Algorithm Design detailed vieW Clearly there is not enough information in step 2 above so we need to specify the computation in more detail If the initial amount is 1000 and the rate is 01 one percent then after one day Vito Will owe Tony 1000 0110001011000 After two days it39s 1011000011011000 101101100010121000 After three days it39s 10121oooo110121000 1011012100010131000 AND IT39S CLEAR THAT THE GENERAL FORMULA IS time amount0wedinitialam0unt1rate NOW WE CAN EXPRESS THE ENTIRE PROGRAM IN MORE DETAIL AND MORE CONCISELY AS quotPSEUDOCODEquot AN INFORMAL FORTRANLIKE LANGUAGE Input The initialam0unt of a loan the rate of interest per day compounded daily the time in days that the loan is outstanding Output The amount0wed 1 Enter or read in initialam0unt rate time 2 Calculate amount0wedin itialam0untl rate time 3 Output on screen or printer amount0wed PSEUDOCODE IS A quotMISHMASHquot AND IS INTENDED TO GUIDE THE PROGRAMMER WHO MUST EVENTUALLY WRITE SYNTACTICALLY CORRECT INSTRUCTIONS TO CARRY OUT THE ALGORITHM SOMETIMES PSEUDOCODE MAY BE EXPRESSED IN A FLOW DIAGRAM BEGIN ENTER initialiamoum rate lime V CALCULATE amounliowedinilialiam0unI I rale Iime V DISPLAY amountiowed STEP 3 PROGRAM CODING IF STEPS ONE AND TWO ARE DONE PROPERLY STEP 3 WILL GO SMOOTHLY IN THIS STEP WE IMPLEMENT DATA OBJECTS AND ALGORITHMS IN THE ACTUAL PROGRAMMING LANGUAGE FORTRAN IN OUR PARTICULAR CASE PROGRAM InterestiRate This program calculates the amount owed to fully repay a loan where the initial loan amount the daily interest rate compounded daily and the duration of the loan in days is given Variables used are initialiamount amount of original loan time duration of loan in days amountiowed amount to fully repay the loan Input initialiamount rate time Output amountiowed w w w w l 1 rate the daily interest rate w w w w IMPLICIT NONE REAL 39 initialiamount rate time amountiowed 1 Get values of initialiamount rate time amountiowed WRITE quotEnter initial amount of loan the rate and the time separated by spaces READ initialiamount rate time 1 Calculate the amount owed at the given rate after the specified number of days amountiowedinitialiamount l Orate time 1 Display amountiowed WRITE 500 amountiowed 500 EORMAT lOX39The amount owed is39 ElO2 END PROGRAM InterestiRa e CLEARLY THIS IS TOO SMALL TO READ SO WE39LL RUN IT FROM EOS EACH STATEMENT IS EXPLAINED IN LECTURE STEP 4 EXECUTION AND TESTING IDEALLY WE39D LIKE TO PROVE OUR PROGRAM IS CORRECT AND WE39LL LOOK AT HOW TO DO THAT IN SIMPLER CASES LATER ON IN THE COURSE FOR NOW WE WILL AT LEAST SHOW THAT IT IS LIKELY THAT OUR PROGRAM IS CORRECT BY CHOOSING CASES FOR WHICH WE KNOW THE ANSWER IN ADVANCE THE TESTING DATASET AND CHECKING THE ANSWERS FOR EXAMPLE AT A RATE OF 01 FOR 1 DAY AND A 1000 LOAN WE SHOULD GET A RESULT OF 1010 IT IS TRIED IN CLASS IT IS ALSO USEFUL TO TRY EXTREMAL CASES LIKE ZERO DAYS IT IS TRIED IN CLASS OR A LOAN OF ZERO DOLLARS FOR A LONG TIME TRIED IN CLASS POSSIBLY OTHER CASES TWO PITFALLS AWAIT THE PROGRAMMER ONE IS A SYNTAX ERROR WHICH IS CAUGHT AT CONIPILE TIME LET39S LEAVE OUT A COMMA AND SEE WHAT HAPPENS TRIED IN CLASS THIS IS A CONIPILETIME ERROR THE SECOND PITFALL IS A RUNTIME ERROR WHICH OCCURS WHEN YOU ATTEMPT TO DO SOMETHING UNPREDICTABLY IMPOSSIBLE FOR EXAMPLE TAKE THE SQUARE ROOT OF A NEGATIVE NUMBER IN OUR CASE IF WE MISTYPED AN INPUT AS 1000 101 105 WE WOULD BE ATTEMPTING TO RAISE A NEGATIVE NUMBER TO A NEGATIVE FRACTIONAL POWER WHICH IS NOT DEFINED IN MATHEMATICS ONE FINAL IMPORTANT POINT TESTING CAN ONLY SHOW THE PRESENCE OF ERRORS NOT THEIR ABSENCE IT CANNOT PROVE THAT THE PROGRAM IS CORRECT IT CAN ONLY SHOW THAT IT IS INCORRECT THUS IN SOME SENSE TESTING IS NEVER COMPLETE IT IS ONLY STOPPED Proofs 0n nonexistence are difficult STEP 5 PROGRAM MAINTENANCE FOR US THE LIFE CYCLE OF A PROGRAM IS THE LENGTH OF THE SEMESTER IN ACTUAL SOFTWARE SYSTEMS WHICH ARE PUT INTO PRODUCTION AFTER TESTING IS STOPPED THE FOLLOWING MAY OCCUR 1 OBSCURE BUGS OR FLAWS NOT DETECTED DURING TESTING MAY SURFACE THEY HAVE TO BE FIXED 2 PERFORMANCE INIPROVEMENT MAY BECOME APPARENT ONCE IN PRODUCTION AND MAY BE PERFORMED 3 CHANGES MAY BE NEEDED TO ENSURE COMPATIBILITY WITH NEW HARDWARE OR SYSTEM SOFTWARE 4 CHANGES IN THE REAL WORLD SUCH AS BUILDING CODES MIGHT FORCE CHANGES IN A CONSTRUCTIONCOST PROGRAM IMPORTANT A WELL STRUCTURED WELL DOCUMENTED PROGRAM IS EASIER TO MODIFY THAN ONE THAT IS POORLY DESIGNED


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.