instructor: dr. henry neeman tas: ashwin seshadri, hisham...

30
CS 1313 010 Computer Programming in Fortran 90 & C Instructor: Dr. Henry Neeman TAs: Ashwin Seshadri, Hisham Qureshi Prerequisite: MATH 1523 (Elementary Functions) or equivalent Class Meetings: Tues/Thurs 10:30-11:45am GLCH 123 Lab sections: Fridays 10:30am, 1:30pm & 2:30pm Carson 206 Note: this class is NOT for students majoring in CS or enrolled in CS option programs.

Upload: others

Post on 24-Oct-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

  • CS 1313010Computer Programming

    in Fortran 90& C

    Instructor: Dr. Henry NeemanTAs: Ashwin Seshadri,Hisham Qureshi

    Prerequisite:MATH 1523(ElementaryFunctions)or equivalent

    ClassMeetings:Tues/Thurs10:30-11:45amGLCH 123Labsections:Fridays10:30am,1:30pm& 2:30pmCarson206

    Note: this classis NOT for studentsmajoringin CSor enrolledin CSoptionprograms.

  • Announcements13January 2000

    Office Hours� HenryNeeman

    SarkeysEnergy Center1252Tuesdays& Thursdays12:15-1:15pm(right afterclass)

    � HishamQureshiCarsonEngineeringCenterB8Mondays& Wednesdays10:00-11:30am

    � AshwinSeshadriCarsonEngineeringCenterB18Mondays& Wednesdays3:00-4:30pm

    A NoteAbout the Fortran 90Textbook

    I spoke with Prof. LakshmivarahanTuesdayafternoon,andappar-ently the5th and6th editionsof Programming in Fortran 90/95 arebasicallythesamebook.King Kopy (Lindsey & Jenkins)hasthe6thedition,which youshouldbuy.

    An ExcellentResource

    C.-K. Shene’sFortran90Tutorial (linkedfrom theclasswebpage)http://www.cs.mtu.edu/shene/COURSES/cs201/NOTES/fortran.html

  • Outline of Fortran 90 Topics

    � Overview of Computing� ComputerOrganization� Languages� ProblemSolving

    � Variables� DataTypes� BasicDataTypes� 1D Arrays� DerivedDataTypes� Assignments

    � Expressions� Numeric� Non-numeric

    � ControlStructures� Branching� Repetition

    � Procedures� Subroutines� Functions

    � Modularity� Modules� InterfaceBlocks

    � Input/Output� Formatting� Files

    Note: this is roughly how thispartof thesemesterwill go.

  • What’ sAll This RAM/ROM Stuff?

    Abbrev Name Read? Write? Addressing Volatile?

    RAM RandomAccessMemory Yes Yes Arbitrary YesROM ReadOnly Memory Yes No Arbitrary No

    In day-to-dayconversation,“RAM” meansthesamethingas“memory.”Both referto mainmemory.

    CDROM

    WhenaCD holdsdatainsteadof music,it actsverymuchlikeROM:� it canonly bereadfrom, but not written to;� it’s nonvolatile;� it canbeaddressedessentially arbitrarily.

    Disadvantageof CDROM comparedto ROM:� slower (CDROM 7 MB/sec,ROM 100MB/sec)

    Advantagesof CDROM comparedto ROM:� muchcheaper� canhavearbitraryamountof storage(onmany CDs)

  • Bits, Bytes,Words, etc

    � Bit (BinarydigIT )� Tiniestpossiblepieceof memory� Possiblevalues:0 or 1, Falseor True,Off or On� Bits aren’t individually addressable: youcan’t reador write justone

    bit to memory

    � Byte: apackageof 8 bits (typically)� Onmostplatforms (kindsof computers),thesmallestaddressable

    pieceof memory:youcanreador write anindividual byte� Possiblevalues:0..255,-128..127

    Canalsorepresentacharacter(e.g.,letter, digit, punctuation)

    � Word: apackageof 4 or 8 contiguousbytes(typically)� Onsomeplatforms(e.g.,CrayJ90),thesmallestpossibleaddressable

    pieceof memory� Standardsizefor storinganumber(integeror real)

  • Putting Bits Together

    ��� �2 possiblevalues(0, 1)

    � �4 possiblevalues(0, 1, 2, 3)

    �� �8 possiblevalues(0, 1, 2, 3, 4, 5, 6, 7)

    �� �16possiblevalues(0, 1, 2, 3, 4, 5, 6, 7, ... , 15)

    ...��� �

    256possiblevalues(0, 1, 2, 3, ... , 255)

    ...� ��� �

    1,024possiblevalues

    ...� ��� �

    65,536possiblevalues

    ...� �� �

    4,294,967,296values(typical sizeof anintegerin mostcomputerstoday)

  • Powersof 2

    ��� = 1��� = 2��� = 4��� = 8��� = 16��� = 32�� = 64�"! = 128��# = 256��$ = 512���%� = 1,024� �&� = 2,048� � � = 4,096��� � = 8,192� �'� = 16,384� � � = 32,768��� = 65,536���(! = 131,072� �%# = 262,144���%$ = 524,288��� � = 1,048,576

  • Kilo, Mega,Giga, Tera, Peta

    Kilobyte: �)+* bytes , 1,024bytes - 1,000bytesApproximatesize:onee-mail(plain text)

    DesktopExample:TRS-80w/4 KB RAM (1977)

    Megabyte: /.0* bytes , 1,048,576bytes - 1,000,000bytesApproximatesize:30phonebookpages

    DesktopExample:IBM PS/2PCw/1 MB RAM (1987)

    Gigabyte: /10* bytes , 1,073,741,824bytes - 1,000,000,000bytesApproximatesize:15copiesof theOKC whitepages

    Desktop:c. 1997

    Terabyte: 324* bytes , 1,099,511,627,776bytes - 1,000,000,000,000bytesApproximatesize:5500copiesof aphonebooklisting everyonein theworld

    Desktop:???

    Petabyte: /50* bytes - 1,000,000,000,000,000bytesDesktop:???

    Moore’sLaw: computingpowerandcapacitydoublesevery year

    Actually, GordonMoore(ChairmanEmeritus,Intel Corp)observedin 1965the“doubling of transistordensityon amanufactureddie every year.” Usually, this ishedgedby sayingthatcomputingpowerdoublesevery18-24months.See:

    http://developer.intel.com/update/archive/issue2/feature.htm

  • Programming LanguageHierar chy

    � High Level Languages� Examples:Fortran,C, Java,HTML� Usuallyarestandardized,socanbeusedonany kind of com-

    puter� Typically aredesignedfor aparticularkind of applicatione.g.,Fortranfor scientificapplications,C for operatingsys-temdesign,HTML for webpages,SASfor statistics

    � AssemblyLanguage:specificto a particularCPUSetof simplecommands(e.g.,loada valuefrom a locationin memory;addtwo numbers;storea valueinto a locationin memory)

    � MachineLanguage:binarycodethattheCPUunderstandsdirectly; binaryrepresentationof assemblylanguage

  • Converting BetweenLanguages

    Compilers,interpretersandassemblersareprogramsthatturnprogramspeoplecanreadinto programscomputerscanrun.

    Compiler� convertsa high level languagesourcecodeof a programinto a

    machinelanguageexecutable� all at once� mustbecompletedbeforeexecutingtheprogram� Examples:Fortran,C

    Interpreter� converts a high level languagesourcecodeinto machinelan-

    guage� convertsandexecutesonestatementat a time� conversionandexecutionoccurwhile running� Examples:Perl,HTML, SAS,Mathematica

    Assembler� convertsaCPU-specificassemblycodeinto machinelanguage� likea compiler, but low level

  • Our Old Friendhelloworld.f90

    scarecrow 212% script helloworld.scriptScript started on Sat Jan 8 12:53:02 200scarecrow 1% cat helloworld.f90

    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Program: helloworld !!!!!! Module: main !!!!!! Author: Henry Neeman 123-45-6789 !!!!!! Class: CS 1313 010 Spring 2000 !!!!!! Lab: Sec 013 Fridays 2:30pm !!!!!! Description: Prints the sentence !!!!!! ’Hello, world.’ to standard !!!!!! output. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!PROGRAM helloworld!! Declarations!! No implicitly typed variables.IMPLICIT NONE!! Execution!! Print the sentence to stdout.PRINT *, ’Hello, world!’

    END PROGRAM helloworldscarecrow 2% f90 -o helloworld helloworld.f90scarecrow 3% helloworldHello, world!

    scarecrow 4% ctrl-DScript done on Sat Jan 8 12:53:22 200scarecrow 213%

  • Executable: helloworld

    Linker/Loader

    helloworld.f90F90 Source Code:

    Assembly Code: helloworld.s

    Assembler

    Object File: helloworld.o

    Compilingf90 -o helloworld helloworld.f90

    compilercalled by

    Automatically

    Compiler

  • Executable: helloworld

    Linker/Loader

    Lexical Analysis

    Parsing

    Semantic Analysis

    Intermediate Code Generation

    Optimization

    Assembly Code Generation

    helloworld.f90F90 Source Code:

    Assembly Code: helloworld.s

    Assembler

    Object File: helloworld.o

    Compiler Detailsf90 -o helloworld helloworld.f90

    Com

    pile

    r

  • Elementsof a Compiler

    Compiler� Lexical Analyzer:identifiesprogram’s“word” elements

    � Comments(ignored)� Keywords (e.g.,PROGRAM, END)� Constants(e.g.,5, ’Hello, world!’, .TRUE.)� User-definedIdentifiers (e.g.,helloworld)� Operators; e.g.6 arithmetic:

    + - * / **6 relational:== /= < >=6 logical:.AND. .OR. .NOT.

    � Parser:determinestheprogram’sgrammar� SemanticAnalyzer:determineswhattheprogramdoes� IntermediateCodeGenerator:expresses,as an assembly-like

    program,whattheprogramdoes� Optimizer:makescodemoreefficient� AssemblyCodeGenerator:producesthe final assemblycode

    thatrepresentswhattheprogramdoes

    Assembler:convertsassemblycodeto machinecode

    Linker/Loader:createsthefinal, executableversionof themachinecode

  • Assembly Code Generation

    Lexical Analysis

    Parsing

    Semantic Analysis

    Intermediate Code Generation

    Compiling a Fortran 90 Statement

    Load R00 from aLoad R01 from bR02 = R00 + R01

    Store R02 into aplusb

    ld r00,ald r01,b

    ad r02,r00,r01st r02,aplusb

    ASSIGN(VARIABLE[aplusb],ADDITION(VARIABLE[a],VARIABLE[b]))

    ASSIGN

    EXPRESSION

    IDENTIFIER[aplusb] ASSIGN IDENTIFER[a] PLUS IDENTIFIER[b]

    ADD

    VARIABLEVARIABLE

    VARIABLE

    aplusb = a + b

  • AssemblyCodefor helloworld.f90on a DEC Alpha

    ldah $gp, ($27)!gpdisp!1

    unop

    lda $gp, ($gp)!gpdisp!1

    unop

    ldq $27,

    for_set_reentrancy($gp)!literal!2

    lda $sp, -96($sp)

    stq $26, ($sp)

    ldq $16, $$5($gp)!literal!3

    jsr $26, ($27),

    for_set_reentrancy!lituse_jsr!2

    ldah $gp, ($26)!gpdisp!4

    mov 12, $1

    lda $gp, ($gp)!gpdisp!4

    ldq $27,

    for_write_seq_lis($gp)!literal!5

    ldq $3, $$7($gp)!literal!6

    ldah $18, 901($31)

    stl $31, 8($sp)

    stq $1, 72($sp)

    lda $16, 8($sp)

    stq $3, 80($sp)

    mov -1, $17

    ldq $19, $$3($gp)!literal!7

    lda $18, -256($18)

    lda $20, 72($sp)

    jsr $26, ($27),

    for_write_seq_lis!lituse_jsr!5

    ldah $gp, ($26)!gpdisp!8

    ldq $26, ($sp)

    lda $gp, ($gp)!gpdisp!8

    mov 1, $0

    lda $sp, 96($sp)

    ret ($26)

    AssemblyCodefor helloworld.f90on a Pentium III

    pushl %ebp

    movl %esp,%ebp

    subl $24,%esp

    movl $.C1_283,%eax

    movl %eax,(%esp)

    call pghpf_init

    movl $14,%eax

    movl %eax,8(%esp)

    movl $.C1_297,%edx

    movl %edx,4(%esp)

    movl $.C1_300,%ecx

    movl %ecx,(%esp)

    call pgf90io_src_info

    movl $.C1_283,%edx

    movl %edx,12(%esp)

    movl %edx,8(%esp)

    movl $pghpf_0_+8,%eax

    movl %eax,4(%esp)

    movl $.C1_301,%ecx

    movl %ecx,(%esp)

    call pgf90io_ldw_init

    movl %eax,-4(%ebp)

    movl $13,%eax

    movl %eax,16(%esp)

    movl $.C1_304,%ecx

    movl %ecx,12(%esp)

    movl $.C1_283,%edx

    movl %edx,8(%esp)

    movl $.C1_285,%eax

    movl %eax,4(%esp)

    movl $.C1_298,%ecx

    movl %ecx,(%esp)

    call pgf90io_ldw

    movl %eax,-4(%ebp)

    call pgf90io_ldw_end

    movl %eax,-4(%ebp)

    movl $.C1_283,%eax

    movl %eax,(%esp)

    call pgf90_exit

    leave

    ret

  • AssemblyCodefor helloworld.f90on a DEC AlphaUsingFortran 90

    ldah $gp, ($27)!gpdisp!1

    unop

    lda $gp, ($gp)!gpdisp!1

    unop

    ldq $27,

    for_set_reentrancy($gp)!literal!2

    lda $sp, -96($sp)

    stq $26, ($sp)

    ldq $16, $$5($gp)!literal!3

    jsr $26, ($27),

    for_set_reentrancy!lituse_jsr!2

    ldah $gp, ($26)!gpdisp!4

    mov 12, $1 ================>>>

    lda $gp, ($gp)!gpdisp!4

    ldq $27,

    for_write_seq_lis($gp)!literal!5

    =============================>>>

    ldq $3, $$7($gp)!literal!6

    ldah $18, 901($31) ==========>>>

    stl $31, 8($sp)

    stq $1, 72($sp) ==========>>>

    lda $16, 8($sp) ==========>>>

    stq $3, 80($sp) ==========>>>

    mov -1, $17 ==========>>>

    ldq $19, $$3($gp)!literal!7

    lda $18, -256($18) =========>>>

    lda $20, 72($sp)

    jsr $26, ($27),

    for_write_seq_lis!lituse_jsr!5

    ldah $gp, ($26)!gpdisp!8

    ldq $26, ($sp)

    lda $gp, ($gp)!gpdisp!8

    mov 1, $0

    lda $sp, 96($sp)

    ret ($26)

    AssemblyCodefor helloworld.f90on a DEC AlphaUsingFortran 95

    ldah $gp, ($27)!gpdisp!1

    unop

    lda $gp, ($gp)!gpdisp!1

    unop

    ldq $27,

    for_set_reentrancy($gp)!literal!2

    lda $sp, -96($sp)

    stq $26, ($sp)

    ldq $16, $$5($gp)!literal!3

    jsr $26, ($27),

    for_set_reentrancy!lituse_jsr!2

    ldah $gp, ($26)!gpdisp!4

    ldah $18, 388($31)

  • Machine Codefor helloworld.f90

    10111101010100010101011110101001

    10111010101000010101101011101000

    01110101010000101011010111010001

    01010100101010101101010101011010

    ...

    How to Program in Machine LanguageDir ectly

    (1) Write assemblycodefor theprogramdirectly by hand.(2) For eachassemblylanguageopcode, look up theassociatedmachinecodebit pattern.(3) On thecomputerconsole,flip switchesto matchthemachinecode.(4) Pressthe“Run” button.

    Actually, on moderncomputers,programmingin machinelanguagedirectly is justaboutimpossible.

  • Fun and easy!

    ApplicationProblem

    ApplicationProblem

    Executable

    ApplicationProblem

    ExecutableProgramming in

    High Level LanguageCompiling

    ApplicationProblem

    Programming inHigh Level Language

    Why Not Do Everything in Assembly Language?

    Executableonly for

    Pentiums

    Programming in

    Assembly LanguagePentium

    Programming inMachine Language

    Why Not Do Everything in Machine Language?

    Not nearly as tedious or error-prone!

    Incredibly tedious and ridiculously error-prone!

    forDEC Alpha

    Compiling Executablefor

    Alphas

    forPentium

    Compiling Executablefor

    Pentiums

    forSGI/MIPS

    Compiling Executablefor

    SGI/MIPS

    Can’t be run on any other kind of computer.May be completely obsolete in a few years.

  • Run

    Bugs?

    Bugs?

    Compile

    Write Program

    Choose Programming Language

    Construct Algorithm

    Debug

    The Programming Process

    Yes

    Yes

    No

    No

    Formulate Problem

    Get an A/Impress Your Boss/Sell for Zillions!

  • What Is an Algorithm?

    An algorithm is a step-by-stepmethodfor solving a well-definedproblemusingfinite resources(computingtimeandmemory).

    Example: Eating a Bowl of Corn Flakes� Getbowl from cupboard� Getspoonfrom drawer� Getboxof cornflakesfrom pantry� Getjug of milk from refrigerator� Placebowl, spoon,cornflakesandmilk on table� Openbox of cornflakes� Pourcornflakesfrom box into bowl� Openjug of milk� Pourmilk from jug into bowl� Closejug of milk� Returnjug to refrigerator� Goto table� Pick upspoon� Repeatuntil bowl is emptyof cornflakes

    � Usingspoon,pick up cornflakesandmilk from bowl� Putspoonwith cornflakesandmilk into mouth� Pull spoonfrom mouth,leaving cornflakesandmilk� Repeatuntil mouthfulis mush6 Chew� Swallow� Leavemessfor housematesto cleanup

  • An Exampleof the Programming Process

    The Problem

    I haveasavingsaccountthatgets5.25%interestayear(compoundedcontinuously)andhas 7 500in it.My officemateDanhasasavingsaccountthatgets5.35%interestayear(compoundedcontinuously)andhas 7 750in it.Eachof uswantsto know how muchinterestwe’ll earnin a year’stime.

    The Algorithm8 9 : ;=

    where:

    ?A@ � �CBEDCFHG��GIFJG��GKMLONQPKML ...?SR is theannualinterestrate?UT is thetime in years?WV is theprincipalin thebankat thestartof theyear?YX is theamountin thebankat theendof theyear

    Note: youcanfind this formulain any calculusbook.

    The Programming Language

    Fortran90,of course!

  • Check Principal

    Check Time

    Input Principal

    Input Rate

    Check Rate

    Input Time

    Compound Interest Algorithm in Detail

    Output Amount

    Compute Amount

  • CodeDevelopmentPart 1

    % cat interest.f90PROGRAM interestIMPLICIT NONEREAL :: principal, rate, time, amountPRINT *, ’This program computes continuously compounded interest.’PRINT *, ’What is the principal, in dollars?’READ *, principalIF (principal < 0.0) THENPRINT *, ’Error: the principal ’, principal, ’ is negative.’STOP

    END IFPRINT *, ’What is the interest rate, in percent?’READ *, rateIF (rate

  • CodeDevelopmentPart 2

    % cat interest.f90PROGRAM interestIMPLICIT NONEREAL :: principal, rate, time, amountPRINT *, ’This program computes continuously compounded interest.’PRINT *, ’What is the principal, in dollars?’READ *, principalIF (principal < 0.0) THENPRINT *, ’Error: the principal ’, principal, ’ is negative.’STOP

    END IFPRINT *, ’What is the interest rate, in percent?’READ *, rateIF (rate

  • CodeDevelopmentPart 3

    % cat interest.f90PROGRAM interestIMPLICIT NONEREAL :: principal, rate, time, amountPRINT *, ’This program computes continuously compounded interest.’PRINT *, ’What is the principal, in dollars?’READ *, principalIF (principal < 0.0) THEN

    PRINT *, ’Error: the principal ’, principal, ’ is negative.’STOP

    END IFPRINT *, ’What is the interest rate, in percent?’READ *, rateIF (rate

  • % interestThis program computes continuously compounded interest.What is the principal, in dollars?750What is the interest rate, in percent?5.35What is the time of compounding, in years?1After 1.000000 year(s) of compoundingat 5.350000 percent interest a yearon a principal of 750.0000 dollarsthe amount is 791.2178 dollars.

  • The Program for Project #1

    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Project #1: Thinking of a Number !!!!!! Program: mynumber !!!!!! Module: main !!!!!! Author: Henry Neeman 123-45-6789 !!!!!! Class: CS 1313 010 Computer Programming, Spring 2000 !!!!!! Lab: Sec 013 Fridays 2:30pm !!!!!! Description: Asks the user to pick a number within a !!!!!! range, then tells whether the user"s number matches the !!!!!! program"s. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!PROGRAM mynumber

    !! Declarations!! No implicitly typed variables.IMPLICIT NONE! Parameter constants! minnum: the user"s number should be at least this.! minnum: the user"s number should be at most this.! mynum: the number that the computer is "thinking" of.INTEGER,PARAMETER :: minnum = 1, maxnum = 10INTEGER,PARAMETER :: mynum = 5! Local variable! yournum: the user"s chosen number.INTEGER :: yournum!! Execution!! Tell the user the range to choose from.PRINT *, "I’m thinking of a number between ", &minnum, " and ", maxnum, "."

    ! Ask for the user"s number.PRINT *, "What number am I thinking of?"! Input the user"s number.READ *, yournum! Check whether the number is correct.IF ((yournum < minnum) .OR. (yournum > maxnum)) THEN! Idiotproofing: if it"s outside the range, complain.PRINT *, "Hey! That’s not between ", &

    minnum, " and ", maxnum, "!"ELSE IF (yournum == mynum) THEN! If it"s correct, be amazed.PRINT *, "That’s amazing!"

    ELSE IF (ABS(yournum - mynum) == 1) THEN! If they"re within 1, say they"re close.PRINT *, "Close, but no cigar; I had ", mynum, "."

    ELSE! Otherwise, be cruel.PRINT *, "Bzzzt! My number was ", mynum, "."

    ENDIFEND PROGRAM mynumber

  • Typical Project #1Operation

    scarecrow 2% f90 -o mynumber mynumber.f90Linking:scarecrow 3% mynumberI’m thinking of a number between 1 and 10.What number am I thinking of?0Hey! That’s not between 1 and 10!

    scarecrow 4% mynumberI’m thinking of a number between 1 and 10.What number am I thinking of?2Bzzzt! My number was 5.

    scarecrow 5% mynumberI’m thinking of a number between 1 and 10.What number am I thinking of?4Close, but no cigar; I had 5.

    scarecrow 6% mynumberI’m thinking of a number between 1 and 10.What number am I thinking of?5That’s amazing!

    scarecrow 7%

  • Pick 2

    1. Takeoutablanksheetof notebookpaper.2. At thetop,write:

    (a) Name& studentID(b) Class& semester(CS1313ComputerProgramming,

    Spring2000)(c) Labsection,day& time

    3. Directly below, write thenumber1.4. Abouthalfwaydown thepage,write thenumber2.5. For eachnumber, write anissuethatyou’d likeexpandedonor

    clarified. It doesnothave to besomethingwe’vecoveredinclassyet,but it shouldbedirectly relatedto computing.