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.
Syllabus for CS1313010Spring 2000Computer Programming in Fortran 90& C
Class: Tuesdays& Thursdays10:30-11:45am,GeorgeLynnCrossHall 123Instructor : Dr. HenryNeeman,Sarkeys Energy Center1252(Boyd & Jenkins)([email protected],325-5386)Officehours:Tues& Thurs12:15-1:15pm,Sarkeys Energy Center1252OR BY APPOINTMENT AT LEAST 24HOURS IN ADVANCE
Note: pleasecontactmeby e-mailunlessit’ sanemergency; pleasedon’t call theCAPSorComputerScienceofficesif youcan’t find mein my office.
Labs: Fridays10:30-11:20am(section011),1:30-2:20pm(012)or 2:30-3:20pm(013)CarsonEngineeringCenter206
TAs: AshwinSeshadri([email protected]),CarsonEngineeringCenterB18Officehoursto beannounced
HishamQureshi([email protected]),CarsonEngineeringCenterB8Officehoursto beannounced
Prerequisite: MATH 1523(ElementaryFunctions)or equivalentNote: this classis not for studentsmajoringin CSor enrolledin CSoptionprograms.
Material to becoveredProgrammingin Fortran90 (aboutthefirst half of thesemester)Programmingin C (therestof thesemester)
TextsProgramming in Fortran 90/95, 5th ed.,S.Lakshmivarahan& S.K.Dhall, 1999Availableat King Kopy (Lindsey & Jenkins)
Problem Solving & Program Design in C, 3rd ed.,J.R.Hamly & E.B.Koffman,1999
Required work7-10ProgrammingProjects(55%)WeeklyQuizzes(10%): everyTuesdayat 10:30amstartingJan25 (usuallyopenbook)Quizquestionswill betakenverbatimfrom thehomework assignedthepreviousTuesday.
MidtermExam(15%):dateto beannouncedin classFinal Exam(20%):ThursdayMay 4 8:00-10:00am
RecommendedworkReadingswill beassignedmostweeksto supplementthelectures.Weeklyhomeworkswill beassignedeveryTuesdaystartingJan18.Thesewill form thebasisfor thequizzes;they will notbecollectedor graded.
Grading: A: 90%- 100% B: 80%- 89% C: 70%- 79% D: 60%- 69% F: lessthan60%I reserve theright to curve thegradesasI seefit, but thecurvewill notbeharsherthanthis.
WebpostingsAll printedclassmaterials,includinglectureslides,homework assignmentsandprogrammingprojectdescriptions,will bepostedon theclasswebpage:
http://www.ecn.ou.edu/CS1313010/
Syllabus for CS1313010Spring 2000(continued)Computer Programming in Fortran 90& C
E-mailOccasionally, wemayneedto alerttheclasswhenanissuecomesup. You shouldcheckyour
e-mailat leastonceaweek.
ClassPoliciesCredit for programming projects
No latenessdeduction:if turnedin on time (by 11:45amon theduedate)25%deducted:if lateoneclass(by 11:45amtheclassaftertheduedate)No credit: if laterthan11:45amtheclassaftertheduedate
Helping eachotherI encourageyou to discusshomework andprogrammingprojectswith eachother. However,IT IS NOT ACCEPTABLE to copy eachother’swork. Cheatingcanresultin suspensionorexpulsion,soDON’T EVEN THINK ABOUT IT!
Help fr om usIf you havequestionsor you’rehaving troublewith thematerial,weurgeyou to cometalk tousduringofficehours,or to makeanappointment(at least24hoursin advance)to meetatothertimes,or to senduse-mail.
Working on programming projectsDo not wait until thelastminuteto startyourprogrammingprojects.Developingsoftwaretakestime,andmaydependon theavailability andreliability of systemsthatyou havenocontrolover. If thecomputersaredown thenightbeforeaduedate,don’t counton thatbuyingyouextra debuggingtime– it certainlywon’t in therealworld.
Studying for examsDo not wait until thelastminuteto startstudyingfor exams.Thebestway to ensuresuccessis to keepupwith thecoursematerial,andto askquestions.Studentswhoactively participatein lecturesandcometo office hourstypically learnandretainthemateriala lot better.
Will this be on the exam?Yes.Everythingcoveredin class,readings,labs,homeworksandprogrammingprojectsis fairgameunlessspecificallystatedotherwise.
DisabilityAny student in this course who has a disability that may prevent him or her from fullydemonstrating his or her abilities should contact the instructor personally as soon as possible sothat accommodations necessary can be made to ensure full participation and to facilitate youreducational opportunities.Be preparedto bring documentationfrom theOfficeof DisabledStudentServices.
AcademicMisconductAll casesof academicmisconductwill bereportedto theDeanof theappropriateCollegefor
adjudication.
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.
ZIP
compact disc
Hello ...
What is aComputer?
and process data.
A computer isa programmable electronic
device that can store, retrieve
Components of a Computer System
COMPUTER SYSTEM
HARDWARE SOFTWAREPhysicaldevices
Sets ofinstructions
FIRMWARESoftware thatlives on a chip
BASIC I/O
Arithmetic/LogicUnit
Registers
NETWORKING
Modem
PortInternet
MULTIMEDIA
CPU
Hardware Components
HARDWARE
Cache$1600/MB
Main
$2/MBMemory
HardDisk
CDROM
Zip/Jaz/etcDisk
MagneticTape
FloppyDisk
0.03 MB/sec$0.21/MB
1 MB/sec
100 MB/sec
ControlUnit
Proc Speed
etc
Keyboard
Mouse
Printer
Monitor
Amplifier
Speakers
etc
etc
CDROM
STORAGE INPUT/OUTPUT
etc
Joystick
Scanner
StorageSecondary
$0.007-0.04/MB8-40 MB/sec
$0.003/MB7 MB/sec
$0.07-0.14/MB2.4-7.4 MB/sec
$0.003/MB
Central Processing Unit
Registers are very expensive, because they have to be etched directlyinto the CPU.
. . .
Bit ShiftR00 << R01
AddR02 = R00 + R01
CompareR00 < R01? R03 = ~R01
Bit Invert
MultiplyR02 = R00 * R01
Registers
. . .
R00
R01
R03
R02
R63
Arithmetic/Logic Unit
Control Unit
AddR03 = R03 + R63
FetchNext
Instruction
Find Data
Memory
Fetch Datafrom
Memory
. . .
Addresses in
InstructionExecute Store
Result inMemory
IncrementInstruction
Pointer
643210 5 7
1412111098 13 15
222019181716 21 23
. . .
302827262524 29 31
34,359,738,367(32 MB)
Address
Main Memory
Cell or Location Contents
-71
. . .0 1 2 5 6 7 83 4
We can think of memory as one contiguous line of cells.
The Bus
all data travel along it.The bus is the connection from the CPU to main memory;
CPU
Main Memory
Main Memory
Bus
CPU
Yikes!
Main Memory
Bus
CPU-75
There you go!
0x12AD36BC
Bus
CPU putt putt putt ... Main Memory
Zzzzz ...
I want thecontents of
0x12AD36BC.
Bus
CPU Main Memory
Zzzzz ...
Bonk!
I’ll put it in R05.
Bus
CPU Main Memory
Zzzzz ...Bonk! -75
Load
Loading Data from Main Memory into the CPU
Load
0x12AD36BC
Cache
CPU
Main Memory
Cache
The CPU runs at, say, 500 MHz. Main Memory transfers run at, say, 100 MHz.So transferring data directly between the CPU and Main Memory is a bottleneck.
Cache is a smaller memory that runs at the same speed as the CPU.
SecondaryStorage
� Nonvolatile: datadon’t disappearwhenpower is turnedoff� Slowerandcheaperthanmainmemory� Most areportable:canbeeasilyremovedfrom yourcomputerand
takento someoneelse’s
Medium Size Speed Type Can Port- Popular? Drive Media(GB) (MB/sec) write? able? (
�) (
�/MB)
HardDisk 9-36 8.5-40.5 Mag Yes No Very 0.007-0.04/MBDVD 17 up to 13 Optic No Yes Not yet 100-300 —
Mag Tape 7 1 Mag Yes Yes Yes 100-1000 0.003DVD-RAM 5.2* 2.7 Optic Yes Yes New! 800 0.009
JazDisk 1-2 5.4-7.4 Mag Yes Yes No 350 0.07CDROM 0.63 up to 7 Optic No Yes Very 30-40 0.003CD-RW 0.63 6R/1.8W Optic Yes Yes No 170-350 0.003
SuperDisk 0.12 up to 0.7 Mag Yes Yes Not very 90-200 0.06Zip Disk 0.10 2.4 Mag Yes Yes Kind of 70-250 0.14Floppy 0.0014 0.03 Mag Yes Yes Very 10-20 0.21Cassette « 0.001 « 1 Mag Yes Yes No Historical
PaperTape « 0.001 « 1 Paper Once Yes No HistoricalPunchCard « 0.001 « 1 Paper Once Yes No Historical
Note: all numbersareapproximateasof 10 January2000.* DVD-RAM capacitywill probablygrow to about15 GB in thenext few years.
MediaTypes� Magnetic:read/write,but degradeover timeandcanbeerasedby magnets� Optical:oftencan’t write, but degradeslowly andcan’t beerasedby magnets� Paper:forgetaboutit!
Software Components
SOFTWARE
SYSTEM APPLICATIONSOFTWARESOFTWARE
You buy these. You write these.
SYSTEM SOFTWARE
COMPILERS/INTERPRETERS
C
C++
Java
Perl
Fortran 90
FUNCTIONLIBRARIES
BLAS
LAPACK
NetCDF
NCAR Graphics
LINPACK
HDF
Kinds of System Software
vi
pico
LaTeX
MS Word
TEXTPROCESSORS
SPREADSHEETS
SAS
Mathematica
Maple
Matlab
SYSTEMSMATH/STATS
Oracle
Sybase
dBASE
MS Access
DATABASES
MS Excel
Lotus
BSD
AIX
HP-UX
IRIX...
Linux
Unix
SYSTEMSOPERATING
Windows
MacOS
PalmOS
OS/2
MSDOS
HTML
csh
etc.
A SimpleFortran 90Program
scarecrow 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%
The SameProgram Without Comments
PROGRAM helloworldIMPLICIT NONEPRINT *, ’Hello, world!’
END PROGRAM helloworld
Some Basic Elements of a Fortran Program
!!! output. !!!
!!! Class: CS 1313 010 Spring 2000 !!!
!!! Description: Prints the sentence !!!!!! ’Hello, world.’ to standard !!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!PROGRAM helloworld!! Declarations
! No implicitly typed variables.IMPLICIT NONE
!
!assumptions about any ofTells compiler to make no
the program’s variables! Execution!! Print the sentence to stdout.PRINT *, ’Hello, world!’
END PROGRAM helloworldEnd statement
Program statement
Program body
!!! Module: main !!!
Comment Block
!!! Author: Henry Neeman 123-45-6789 !!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Program: helloworld !!!
!!! Lab: Sec 013 Fridays 2:30pm !!!
Languages
� Kindsof Languages� Natural� Programming
� ConvertingBetweenProgrammingLanguages� Compilers� Interpreters� Assemblers
Kinds of Languages
NaturalLanguages� Examples:English,Chinese,Swahili, Navajo,Quechua,
Maori� Typically canbedescribedby formal rules� Might notbeboundby theserulesin everydayuse
“Any nouncanbeverbed.”“I might couldgetmeoneo’ themtherecomputers.”
� Canmix wordsandsyntaxfrom multiple languagesin onesentence“Hey, amigo,is it all right by you if I kibbitz yourchessgamewhile I watchyouranime?”
� Canbeambiguous“Whendid hesayshewasgoing?”Statethetime atwhich hesaid,“Shewasgoing.”Accordingto him, atwhattime wasshegoing?
ProgrammingLanguages� Completelydescribedandboundby formal rules� Cannotmix wordsandsyntaxfrom multiple languages� Cannotbeambiguous� WordsandsyntaxmustbeEXACTLY correct
Programming LanguageHierar chy
� High Level Languages� Examples:Fortran,C, Java,HTML� Usuallyarestandardized,socanbeusedonany kind of com-
puter� Typically aredesignedfor aparticularkind of application
e.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)� User-definedIdentifiers (e.g.,helloworld)� Operators; e.g.
arithmetic:+ - * / ** comparisons:.EQ. .NE. .LT. .LE. .GT. .GE.
arraysubscripting:( )� 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 a into R00Load b into R01R02 = 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] EQUAL 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) <<<============
lda $gp, ($gp)!gpdisp!4
ldq $27,
for_write_seq_lis($gp)!literal!5
mov 12, $1 <<<==================
ldq $3, $$7($gp)!literal!6
lda $18, -31489($18) <<<=========
stl $31, 8($sp)
lda $16, 8($sp) <<<=============
stq $1, 72($sp) <<<=============
mov -1, $17 <<<=============
stq $3, 80($sp) <<<=============
ldq $19, $$3($gp)!literal!7
sll $18, 8, $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)
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!
A LessSimpleFortran 90 Program
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Program: mynumber !!!!!! Author: Henry Neeman !!!!!! Class: CS 1313 010 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 .LT. minnum) .OR. (yournum .GT. maxnum)) THEN! Idiotproofing: if it’s outside the range, complain.PRINT *, ’Hey! That’’s not between ’, minnum, &
& ’ and ’, maxnum, ’!’ELSE IF (yournum .EQ. mynum) THEN! If it’s correct, be amazed.PRINT *, ’That’’s amazing!’
ELSE IF (ABS(yournum - mynum) .EQ. 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
A LessSimpleFortran 90Program’s Output
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%