software development for engineers, c/c++, pascal
TRANSCRIPT
SoftwareDevelopmentforEngineers
withC,Pascal,C++,AssemblyLanguage,VisualBasic,HTML,JavaScriptandJava
WilliamJ.Buchanan,BSc,CEng,PhDSeniorLecturer,DepartmentofElectricalandElectronicEngineering,NapierUniversity,Edinburgh,UK
TableofContents
Coverimage
Titlepage
Dedication
Copyright
Preface
PARTA:C/PASCAL
Chapter1:Introduction
1.1Introduction
1.2Hardware,SoftwareAndFirmware
1.3BasicComputerArchitecture
1.4Compiling,LinkingAndProducingAnExecutableProgram
1.5CCompilation
1.6PascalCompilation
1.7IntroductionToC
1.8IntroductionToPascal
1.9Exercises
Chapter2:Input/Output
2.1Introduction
2.2PascalInput/Output
2.3CInput/Output
2.4Examples
Chapter3:SelectionStatements
3.1If…ElseStatements
3.2SwitchStatement
3.3Exercises
Chapter4:RepetitiveStatements
4.1Introduction
4.2For
4.3Examples
4.4Exercises
4.5While()
4.6Repeat..Until()AndDo..While()
4.7Examples
4.8Exercises
Chapter5:Functions
5.1Introduction
5.2ArgumentsAndParameters
5.3CFunctions
5.4PascalFunctions
5.5Examples
5.6Exercises
Chapter6:ParameterPassing
6.1Introduction
6.2PascalParameterPassing
6.3CParameterPassing
6.4Examples
6.5Exercises
Chapter7:Arrays
7.1Introduction
7.2CArrays
7.3PascalArrays
7.4Examples
7.5Exercises
Chapter8:Strings
8.1Introduction
8.2PascalStrings
8.3CCharacterArrays
8.4Examples
8.5Exercises
Chapter9:FileI/O
9.1Introduction
9.2PascalFileI/O
9.3CFileI/O
9.4Examples
9.5ReadingAndWritingOneCharacterAtATime
9.6Exercises
Chapter10:StructuresandRecords
10.1Introduction
10.2RecordsInPascal
10.3StructuresInC
10.4ArrayOfStructures
10.5Exercises
PARTB:C++
Chapter11:IntroductiontoC++
11.1Introduction
11.2EnhancementsToC++
11.3I/OStream
11.4Comments
11.5FunctionOverloading
11.6Classes
11.7ComplexNumbers
11.8Exercises
Chapter12:MoreC++
12.1ConstructorsAndDestructors
12.2FunctionTemplates
12.3ClassTemplates
12.4I/OStreams
12.5Exercises
PARTC:AssemblyLanguage
Chapter13:Introduction
13.1Introduction
13.2BasicComputerArchitecture
13.3BitsAndBytes
13.4BinaryArithmetic
13.5NumbersAndRepresentations
13.6MemoryAddressingSize
13.7Exercises
Chapter14:ComputerArchitecture
14.1HistoryOfThePC
14.2IntelMicroprocessors
14.380386/80486Microprocessor
14.4Registers
14.5MemorySegmentation
14.6ViewInsideTheProcessor
14.7MachineCodeAndAssemblyLanguage
14.8Exercises
Chapter15:8086/88Instructions
15.1Introduction
15.2CharactersAndNumbers
15.3Comments
15.4Move(MOV)
15.5AddressingMemory
15.6AdditionAndSubtraction(ADDAndSUB)
15.7Compare(CMP)
15.8UnaryOperations(INC,DECAndNEG)
15.9BooleanBitwiseInstructions(AND,OR,XORAndNOT)
15.10Shift/RotateInstructions(SHL,SAL,SHR,SAR,ROL,ROR,RCLAndRCR)
15.11UnconditionalJump(JMP)
15.12ConditionalJumps
15.13SubroutineCalls(CALLAndRET)
15.14PushAndPop
15.15MovingAroundDataInMemory
15.16AssemblerDirectives
15.17DataDefinition
15.18Equates(EQU)
15.19ExercisesPart1
15.20ExercisesPart2
Chapter16:8086InterfacingandTiming
16.1Introduction
16.2InterfacingWithMemory
16.3MemoryMappedI/O
16.4IsolatedI/O
16.5DigitalI/OUsingThe8255
16.6DigitalI/OPrograms
16.7Timing
16.8Exercises
Chapter17:8086Interrupts
17.1Interrupts(INT)
17.2Interrupt21h:DOSServices
17.3Interrupt10h:BIOSVideoMode
17.4Interrupt11h:BIOSEquipmentCheck
17.5Interrupt13h:BIOSDiskAccess
17.6Interrupt14h:BIOSSerialCommunications
17.7Interrupt17h:BIOSPrinter
17.8Interrupt16h:BIOSKeyboard
17.9Interrupt19h:BIOSReboot
17.10Interrupt1Ah:BIOSSystemTime
17.11CAndPascalInterrupts
17.12Exercises
PARTD:VisualBasic
Chapter18:Introduction
18.1Introduction
18.2Event-DrivenProgramming
18.3VisualBasicFiles
18.4OtherTerms
18.5MainScreen
18.6PropertiesWindow
18.7ControlsAndEvent
18.8Exercises
Chapter19:VisualBasicLanguage
19.1Introduction
19.2ProgrammingLanguage
19.3EnteringAProgram
19.4LanguageReference
19.5Exercises
Chapter20:Forms
20.1Introduction
20.2SettingProperties
20.3FormsAndCode
20.4TemperatureConversionProgram
20.5QuadraticRootsProgram
20.6ResistanceCalculationWithSliderControlsProgram
20.7Exercises
Chapter21:MenusandDialogBoxes
21.1Introduction
21.2MenuEditor
21.3CommonDialogControl
21.4RunningAnApplicationProgram
21.5Exercises
Chapter22:Events
22.1Introduction
22.2ProgramEvents
22.3Exercises
Chapter23:Graphics
23.1Introduction
23.2LoadingGraphicsFiles
23.3Colours
23.4Drawing
23.5Exercises
PARTE:HTML/Java
Chapter24:HTML(Introduction)
24.1Introduction
24.2Links
24.3Lists
24.4Colours
24.5BackgroundImages
24.6DisplayingImages
24.7HorizontalLines
24.8Exercises
Chapter25:FurtherHTML
25.1Introduction
25.2Anchors
25.3Tables
25.4CGIScripts
25.5Forms
25.6Multimedia
25.7Exercises
Chapter26:JavaScript
26.1Introduction
26.2JavaScriptLanguage
26.3JavaScriptValues,VariablesAndLiterals
26.4ExpressionsAndOperators
26.5JavaScriptOperators
26.6JavaScriptStatements
26.7ConditionalStatements
26.8Loops
26.9Comments
26.10Functions
26.11ObjectsAndProperties
26.12DocumentObjects
26.13EventHandling
26.14WindowObjects
26.15ObjectManipulationStatementsAndOperators
26.16Exercises
Chapter27:Java(Introduction)
27.1Introduction
27.2CreatingAnApplet
27.3AppletBasics
27.4Stand-AlonePrograms
27.5JavaReservedWords
27.6AppletVariables
27.7JavaOperators
27.8MathematicalOperations
27.9Loops
27.10ConditionalStatements
27.11Exercises
Chapter28:Java(Extendedfunctions)
28.1Introduction
28.2InitializationAndExitFunctions
28.3MouseEvents
28.4MouseSelection
28.5KeyboardInput
28.6GraphicsImages
28.7Graphics
28.8Sound
28.9DialogBoxes
28.10Fonts
28.11Exercises
PARTF:DOS
Chapter29:Introduction
29.1Introduction
29.2IntroductionToDOS
29.3Disks
29.4FormattingFloppyDisks(FORMAT)
29.5FileSystemStructure
29.6DOSFilenames
29.7FileTypes
29.8ListingFiles(DIR)
Chapter30:DOSFileSystem/Editor
30.1ChangingDirectory(CDOrCHDIR)
30.2MakingADirectory(MKDIROrMD)
30.3ViewingAFile(TYPE)
30.4Wild-Cards(*Or?)
30.5CreatingATextFile
30.8DeletingFiles(DELOrERASE)
30.9CopyingFiles(COPY)
PARTG:Windows3.x
Chapter31:Introduction
31.1Introduction
31.2RunningWindows
31.3WindowsDesktop
31.4WindowItems
31.5MouseControls
31.6ProgramManagerMenus
31.7MovingAndResizingAWindow
31.8ClosingAWindowWithTheControlMenu
31.9Exercises
Chapter32:FileManagement
32.1Introduction
32.2FileManager
32.3Exercises
PARTH:Windows95/NT
Chapter33:Windows95/NT
33.1Introduction
33.2Servers,WorkstationsAndClients
33.3WorkgroupsAndDomains
33.4WindowsNTUserAndGroupAccounts
33.5FileSystems
33.6RunningWindows95AndNT
33.7BasicWindowsNT/95
33.8MouseControls
33.9QuittingWindows
33.10MovingAndResizingAWindow
33.11ClosingAWindowWithTheControlMenu
33.12Start
33.13MyComputer
33.14RunningDOS
33.15Windows95/NTNetworkDrives
33.16Exercises
Chapter34:ExtraWindows
34.1SavingImportantSet-UpFiles
34.2RunningAProgramWhenWindowsStartsUp
34.3CapturingWindowsScreen
34.4SwappingBetweenApplications
34.5TerminatingProgramsWhichHaveCrashed
34.6WindowsFileExtensions
34.7Exercises
PARTI:UNIX
Chapter35:IntroductiontoUNIX
35.1Introduction
35.2LoginIntoTheSystem
35.3DirectoryStructure
35.4On-LineManual
35.5ChangingDirectory
35.6ListingDirectories
35.7FileAttributes
35.8SpecialCharacters(*,?And[])
35.9ListingContentsOfAFile
35.10MakingAndRemovingDirectories
35.11Copying,RenamingAndRemoving
35.12StandardInputAndOutput
35.13CompilingCPrograms
35.14DisplayingTheTimeAndDate
35.15WhereToFindThings
35.16Exercises
35.17Summary
Chapter36:UNIXCommands
36.1ProcessControl
36.2Compilers
36.3FileManipulationCommands
36.4OtherCommands
36.5Exercises
Chapter37:EditingandTextProcessing
37.1Introduction
37.2VisualEditor
37.3ExampleOfTextEditing
37.4SedEditor
37.5Grep
37.6Sort
37.7Exercises
Chapter38:Csh(CShell)
38.1Introduction
38.2EnteringTheCShell
38.3LeavingTheCShell
38.4History
38.5ReexecutingEvents
38.6Alias
38.7Variables
38.8SpecialForms($#,$?And~)
38.9ShellVariables
38.10ShellScripts
38.11ControlStructures
38.12AutomaticallyExecutedCShellScripts(.Login.cshrc)
38.13Exercises
APPENDIXA:JavaClasses
APPENDIXB:ANSI-CFunctions
APPENDIXC:TurboPascalReference
APPENDIXD:AssemblyLanguageReference
APPENDIXE:ASCIICharacterSet
Index
Copyright
FirstpublishedinGreatBritainin1997byArnold,amemberoftheHodderHeadlineGroup,338EustonRoad,LondonNW13BHhttp://www.arnoldpublisher.comCopublishedinNorth,CentralandSouthAmericabyJohnWiley&SonsInc.,605ThirdStreet,NewYork,NY10158-0012©1997WilliamBuchananAllrightsreserved.Nopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronicallyormechanically,includingphotocopying,recordingoranyinformationstorageorretrievalsystem,withouteitherpriorpermissioninwritingfromthepublisheroralicencepermittingrestrictedcopying.IntheUnitedKingdomsuchlicencesareissuedbytheCopyrightLicensingAgency:90TottenhamCourtRoad,LondonW1?9HE.Whilsttheadviceandinformationinthisbookisbelievedtobetrueandaccurateatthedateofgoingtopress,neithertheauthornorthepublishercanacceptanylegalresponsibilityorliabilityforanyerrorsoromissionsthatmaybemade.BritishLibraryCataloguinginPublicationDataAcataloguerecordforthisbookisavailablefromtheBritishLibraryLibraryofCongressCataloging-in-PublicationDataAcatalogrecordforthisbookisavailablefromtheLibraryofCongressISBN0340700149ISBN0471852662(Wiley)Publisher:DavidRossProductionEditor:JamesRabsonProductionController:SarahKettCoverdesigner:TerryGriffithsPrintedandboundinGreatBritainbyJWArrowsmith,Bristol
Preface
Specialization in software development is becoming a thing of the past.PreviouslymanysoftwaredevelopersspecializedonsoftwarelanguagessuchasFORTRAN, C and Pascal. This wasmainly because these languages allowedaccesstoalltherequiredfunctionality.Inmoderntimeswiththemovetowardsgraphical user interface programming a developer must choose not only therequiredsoftwarelanguage(s)butalsotherequiredsetofdevelopmenttoolsforaspecificpurpose.Typicaldecisionmightbeto:•Minimizedevelopmenttime;•Createausableinterface(suchasDOS,orMicrosoftWindowsorX-
Windows,andsoon);•Operatewithincriticaltimings(suchastheuseoffastcode,orthatDOS
programsgenerallyoperatefasterthanMicrosoftWindowsprograms,orthatcompiledprogramsgenerallyworkfasterthaninterpretedprograms);
•Integratewithothersoftwareorsystems(suchastheintegrationwithpreviouswrittensoftware,differentoperatingsystemsorwithprecompiledlibraries);
•Maintainthelong-termdevelopmentoftheprogram(typicalquestionsmightbe:willtherebeupdatestothedevelopmenttools;willthedevelopmentcompanystillbearoundinafewyears?,andsoon).
Typical modern development languages are C/C++, Visual Basic, Ada(especially in military applications), Java and Delphi. This book introducesC/C++whichcanbeusedinC/C++andJavadevelopmentapplications.Pascalis useful in developing Delphi and Ada applications. Visual Basic is used towrite Microsoft Windows applications, and 80X86 Assembly Languageprogramming is useful in writing extremely fast sections of code and inappreciatingtheoperationofthePC.Themainobjectiveof the text is toprovideasinglesourceofreferenceand
learningmaterialformostofthemaintechnicalprogramminglanguages.Itcanbeusedbyundergraduatesthroughacourseofstudyfromfirstyeartofinaland
fromintroductorytutorialworktoadvanceduserinterfacesandprojectwork.Itcanalsobeusedbyprofessionaldeveloperswithaknowledgeofoneormoreofthesoftwaredevelopmentlanguagewhowishtolearnsome,orall,oftheothers,orhowtheselanguagescanbeusedin‘real-life’applications.Thetextsplitsintoninemainsections:PartA:Pascal/Cprogramming–givesanintroductiontostructuredsoftwaredevelopmentusingPascalandC.
PartB:C++programming–givesanintroductiontoobject-orienteddesignwithC++.
PartC:80x86AssemblyLanguageprograms–givesanintroductiontoAssemblyLanguageprogrammingandPCarchitecture.
PartD:VisualBasicprogramming–givesanintroductiontothedevelopmentofgraphicaluserinterfacesforMicrosoftWindows.
PartE:HTMLandJavaprograms–showhowtodevelopWWW-basedpagesandgivesanintroductiontoJava.
PartF:DOS.PartG:Windows3.PartH:Windows95.PartI:UNIX.The text uses C and Pascal to provide a basic grounding in software
development.Theseareusedtoshowstructuredsoftwaredevelopmentconcepts,such as repetition, decision making and modular development. The moreadvanced concepts of object-oriented design is introduced with the C++development.TheVisualBasicsectioncontainsprogramexampleswhichcanbeusedtodevelopgraphicaluserinterfaceprograms.Manysoftwaredevelopmentjobadvertisementsnowspecifytherequirement
for a mixture of software languages on possibly several different operatingsystems.Softwaredevelopmenthasthusevolvedtothepointwhereitispossibleto integrate different software tools to produce the required system. The userinterface of a program might be developed using a graphical programminglanguage such as Visual Basic and various specialized modules within theprogramcouldbedevelopedinC/C++.Insummary,inachangingemploymentmarket:
‘itisessentialtobecomemulti-skilledindifferentareasandapplications’.
1
Introduction
1.1Introduction
Softwaredevelopmenthasgrownover theyearsfromsimpleBASICprogramswritten on small hobby computers to large software systems that controlfactories.Manyapplications thatatone timeuseddedicatedhardwarearenowimplementedusingsoftwareandprogrammablehardware.Thisshiftinemphasishas meant that, as a percentage, an increasing amount of time is spent onsoftwareandlessonhardwaredevelopment.Electrical,electronicandsoftwareengineersrequireagreatdealofflexibility
in theirapproach tosystemdevelopment.Theymusthaveanunderstandingofall levels of abstraction of the system, whether it be hardware, software orfirmware. The system itself could range from a small 4-bit central heatingcontrollertoalargeindustrialcontrolsystem.Inthedevelopmentofanysystemthe engineer must understand the system specification from its interfacerequirements,itstimingrequirements,itselectricalcharacteristics,andsoon.The software that runs on a systemmust be flexible in its structure as the
developercouldrequiretointerrogatememoryaddressesfortheircontentsortomodelapartof thesystemasanalgorithm.For thispurpose theprogramminglanguages C and Pascal are excellent in that they allow a high-level ofabstraction (such as algorithm specification) and allow low-level operations(such as operations onbinarydigits).Theyhave awide rangeof applications,from commerce and business to industry and research, which is a distinctadvantage as many software languages have facilities that make them usefulonly in a particular environment. For example, in the past, business andcommercial applications used COBOL extensively, whereas engineering andscienceusedFORTRAN.
1.2Hardware,softwareandfirmware
Asystemconsistsofhardware,softwareandfirmware,allofwhichinterconnect.Hardware is ‘thebits thatcanbe touched’, that is, thecomponents, the screwsandnuts,thecase,theelectricalwires,andsoon.Softwareistheprogramsthatrun on programmable hardware and change their operation depending on theinputs to the system. These inputs could be taken from a keyboard, interfacehardware or from an external device. The program itself cannot exist withoutsome formof programmable hardware such as amicroprocessor or controller.Firmware is a hardware device that is programmed using software. Typicalfirmware devices areEEPROMs (ElectricallyErasableReadOnlyMemories),andinterfacedevicesthatareprogrammedusingregisters.In most applications, dedicated hardware is faster than hardware that is
runningsoftware,althoughsystemsrunningsoftwareprogramstendtobeeasiertomodifyandrequirelessdevelopmenttime.
1.3BasiccomputerarchitectureThemainelementsofabasiccomputersystemareacentralprocessingunit(ormicroprocessor),memory,andinput/output(I/O)interfacingcircuitry.Theseareinterconnected by threemain buses: the address bus; the control bus; and thedata bus, as illustrated in Figure 1.1. External devices such as a keyboard,display,diskdrives,andsoon,canconnectdirectlyonto thedata,addressandcontrolbuses,orconnectthroughI/Ointerfacingcircuitry.
FIGURE1.1 Blockdiagramofasimplecomputersystem
MemorynormallyconsistsofRAM(randomaccessmemory)andROM(readonlymemory).ROMstores permanent binary information,whereasRAM is anon-permanentmemory and loses its contentswhen the power is taken away.RAM memory is used to run application programs and to store information
temporarily.Themicroprocessor is themaincontrollerof thecomputer. It fetchesbinary
instructions(knownasmachinecode)frommemory,itthendecodestheseintoaseriesofsimpleactionsandcarriesouttheactionsinasequenceofsteps.Thesestepsaresynchronizedbyasystemclock.Themicroprocessoraccessesamemorylocationbyputtingitsaddressonthe
address bus. The contents at this address are placed on the data bus and themicroprocessor reads thedata from thedatabus.To storedata inmemory themicroprocessorplaces thedataon thedatabus.The addressof the location inmemory is thenputon theaddressbusand thedata is thenreadfromthedatabusintotherequiredmemoryaddresslocation.
1.4Compiling,linkingandproducinganexecutableprogramAmicroprocessoronlyunderstandsbinaryinformationandoperatesonaseriesofbinarycommandsknownasmachinecode. It is extremelydifficult towritelargeprogramsinmachinecode,sothathigh-levellanguagesareusedinstead.Alow-level language is one which is similar to machine code and normallyinvolves theusageofkeywordmacros toreplacemachinecode instructions.Ahigh-level language has a syntax that is almost like written English and thusmakes a program easy to read and to modify. In most programs the actualoperationofthehardwareisinvisibletotheprogrammer.A compiler changes the high-level language into machine code. High-level
languagesincludeC,BASIC,COBOL,FORTRANandPascal;anexampleofalow-levellanguageis80386AssemblyLanguage.Figure1.2showsthesequenceofeventsthatoccurtogenerateanexecutable
programfromaCorPascalsourcecodefile(thefilenamesusedinthisexamplerelatetoaPC-basedsystem).Aneditorcreatesandmodifiesthesourcecodefile;acompilerthenconvertsthissourcecodeintoaformwhichthemicroprocessorcan understand, that is, machine code. The file produced by the compiler isnamed an object code file code (note that Turbo Pascal does not produce anobjectcodefile).Thisfilecannotbeexecutedasitdoesnothavealltherequiredinformationtoruntheprogram.Thefinalstageoftheprocessislinking,whichinvolvesaddingextramachinecodeintotheprogramsothatitcanusedevicessuchasakeyboard,amonitor,andsoon.Alinkerlinkstheobjectcodefilewithother object code files and with libraries to produce an executable program.
Theselibrariescontainotherobjectcodemodulesthatarecompiledsourcecode.
FIGURE1.2 Edit,compileandlinkprocesses
If compilation or linking steps generate errors or warnings then the sourcecodemustbemodifiedtoeliminatethemandtheprocessofcompilation/linkingbeginsagain.Warningsinthecompile/linkprocessdonotstopthecompilerorlinkerfromproducinganoutput,buterrorswill.Allerrorsinthecompilationorlinking stage must be eliminated, whereas it is only advisable to eliminatewarnings.
1.5CcompilationBorland C++ Version 3.0 is an integrated development package available forPC-basedsystems.Itcontainsaneditor,compiler,linkeranddebugger(usedtotestprograms).Theeditorcreatesandmodifiessourcecodefilesandisinitiatedby running BC.EXE. Figure 1.3 shows a main screen with a source code filePROG1_1.C.
FIGURE1.3 BorlandC++Version3.0mainscreen
Figure 1.4 shows the compile menu options within this package. A sourcecode file is compiled by selecting Compile to OBJ. If there are no errors anobjectcodefileisproduced(inthiscasePROG_1.OBJ).ThisislinkedusingLinkEXEfile(producingthefilePROG_1.EXE).Acompileandlinkprocesscanalsobe initiated using theMake EXE file option. Programs are run from the Runmenuoption.
FIGURE1.4 BorlandC++Version3.0compilemenuoptions
1.6PascalcompilationTurbo Pascal Version 5.0 is an integrated development package available forPC-basedsystems.Itcontainsaneditor,compiler,linkeranddebugger(usedto
testprograms).TheeditorcreatesandmodifiessourcecodefilesandisinitiatedbyrunningTURBO.EXE.Figure1.5showsamainscreenwithasourcecodefilePROG1_1.PAS.
FIGURE1.5 TurboPascalVersion5.0mainscreen
Figure 1.6 shows the compile menu options within this package. A sourcecode file is compiled by selecting Compile. If there are no errors then anexecutable program is produced. If the destination is given as Memory then itdoes not save the executable file to the disk but runs it frommemory. If thedestinationistotheDiskthenanexecutablefilewillbeproduced(producingthefilePROG_1.EXE). The destination can be toggled by pressing theENTERkeywhile the linecursor ison theDestinationoption.AprogramisrunfromtheRunmenuoption.
FIGURE1.6 TurboPascalVersion5.0compilemenuoptions
1.7IntroductiontoCThissectiongivesabriefintroductiontoANSI-C.
1.7.1PreprocessorThepreprocessoractsonprogramsbefore thecompiler. Itusescommandsthathave a number-sign symbol (‘#’) as the first non-blank character on a line.Figure1.7showsitsmainuses,whichare:includingspecialfiles(headerfiles)and defining various macros (or symbolic tokens). The #include directiveincludesaheader fileand#definedefinesmacros.Byplacing thesedirectivesnearthetopofasourcecodefilethenallpartsoftheprogramhaveaccesstotheinformationcontainedinthem.
FIGURE1.7 Operationsontheprogramtoproduceanexecutablefile
Forexample,thepreprocessordirective:
includestheheaderfilemain.h.Theinvertedcommasinformthepreprocessorthatthisfilewillbefoundinthecurrentworkingdirectory,whilethedirective
includesthefilestdio.hfoundinthedefaultincludedirectory.Thisdirectoryisnormallyset-upautomaticallyby thesystem.Forexample,TurboCVersion2.0storesitsheaderfiles,bydefault,inthedirectory\TC\INCLUDEandBorlandCuses\BORLANDC\INCLUDE.Typically,headerfilesonaUnixsystemarestoredintheusrincludedirectory.To summarize, invertedcommas (” “) inform thepreprocessor to search for
thespecifiedheaderfileinthecurrentdirectory(orthedirectoryspecifiedinthepathname).Thechevroncharacters(<>)informthepreprocessortosearchinthedefaultincludedirectory.Itisnotadvisabletoincludeanyotherfileapartfromheader files. These have a ‘.h’ file extension (although this is not obligatory).Standard header files are used in conjunction with functions contained inlibraries. They do not contain program code, but have information relating tofunctions. A given set of functions, such as maths or I/O, has a header fileassociatedwithit.Table1.1givestypicalheaderfilesandtheirfunctionality.
Table1.1Typicalheaderfiles
Headerfile Comment
ctype.h characterclassificationandconversion
Math.h mathsfunctions
stddef.h definesseveralcommondatatypesandmacros
stdio.h Input/Output(I/O)routines,suchasinputfromkeyboard,outputtodisplayandfilehandling(stdioisacontractionofstandardinput/output)
stdlib.h miscellaneousroutines
string.h stringmanipulationfunctions
time.h timefunctions
Amacroreplaceseveryoccurrenceofacertain tokenwithanotherspecifiedtoken.Thefollowingexamplesshowsubstitutionsusingthe#definedirective.
Typically,asamatterofprogrammingstyle,thedefinitionsofconstants,such
asπ,aregiveninuppercasecharacters.
1.7.2StructureNormallyprogramsaresplitintoanumberofsub-tasksnamedfunctions.Theseare clearly distinctive pieces of code that perform particular operations. Themain function (main ()) is the basic routine for controlling the flow of theprogramandcallsothersub-functions.CProgram1.1isasimpleprogramwhichusestheputs()functiontodisplay
the text “Essence of Software”. The puts() function is a standard functionused to output text to the display; the header file associatedwith it is stdio.h.Thisheaderfileisincludedusingthe#includedirective.Thestatement terminator(;) isused toenda lineofcode(orstatement)and
braces({})showthebeginning({)andend(})ofablockofcode.Commentsareinserted in the program between a start comment identifier (/*) and an endidentifier(*/).
AllCprogramshaveamain()functionwhichdefinestheentrypointintotheprogramand, bymeansof calling functions, controls general program flow. Itcanbelocatedanywhereinthesourcecodeprogram,butisnormallyplacednearthe top of the file it is located in (making it easier to find).Theint keywordpreceding main() defines that the program returns a value to the operatingsystem (or calling program). In this case, the return value is 0 (return (0)).Normally,anon-zeroreturnvalueisusedwhentheprogramhasexitedduetoanerror;theactualvalueofthisgivesanindicationofwhytheprogramhasexited.The void within the parenthesis of main() defines that there is nocommunicationbetweentheprogramandtheoperatingsystem(thatis,novaluesare passed into the program). Figure 1.8 shows the basic structure of a Cprogram.
FIGURE1.8 Cprogramstructure
1.7.3DataTypesVariableswithin aprogramcanbe stored as eithernumbersor characters.Forexample, the resistance of a copperwirewould be stored as a number (a realvalue) and the name of a component (such as, “R1”) would be stored ascharacters.Table1.2givesthefourbasicdatatypeswhichdefinetheformatofvariables.
Table1.2Basicdatatypes
Type Usage
char singlecharacter‘a’,‘1’,andsoon
int signedinteger
float single-precisionfloatingpoint
double double-precisionfloatingpoint
Therearethreebasicextensionsforthefourtypes;theseare:
An integer is any value without a decimal point; its range depends on thenumberofbytesusedtostoreit.Afloatingpointvalueisanynumberandcanincludeadecimalpoint;thisvalueisalwaysinasignedformat.Again,therangedependsonthenumberofbytesused.
Integersnormallytakeup2or4bytesinmemory,dependingonthecompilerimplementation. This gives ranges of –32768 to 32767 (a 2-byte int) and –2147483648to2147483647(a4-byteint),respectively.
1.7.4DeclarationOfVariablesAprogramusesvariablestostoredata.Beforetheprogramcanuseavariable,itsnameanditsdatatypemustfirstbedeclared.Acommagroupsvariablesofthesamedatatype.Forexample,ifaprogramrequiresintegervariablesnum_stepsand bit_mask, floating point variables resistor1 and resistor2, and twocharacter variables char1 and char2, then the following declarations can bemade:
CProgram1.2 isasimpleprogramthatdetermines theequivalentresistanceof two resistors of 1000Ω and 500Ω connected in parallel. It contains threefloating point declarations for the variables resistor1, resistor2 andequ_resistance.
It is also possible to assign an initial value to a variable at the point in theprogram at which it is declared; this is known as variable initialization. CProgram1.3givesanexampleofthiswiththedeclaredvariablesresistor1andresistor2initializedto1000.0and500.0,respectively.
1.7.5KeywordsANSI-C has very few reserved keywords (only 32); these cannot be used asprogramidentifiers.Ciscase-sensitiveandthustheymustbeusedinlowercase.From these simplebuildingblocks largeprogramscanbebuilt.The followinggivesalistofthekeywords.
Functions are sections of code that perform a specified operation. Theyreceive some input and produce an output in a way dictated by theirfunctionality. These can be standardized functions which are inserted intolibraries or are written by the programmer. ANSI-C defines some standardfunctions which provide basic input/output to/from the keyboard and display,mathematical functions, character handling, and so on. They are groupedtogether into library files and are not an intrinsic part of the language. Theselibrarieslinkintoaprogramtoproduceanexecutableprogram.
1.8IntroductiontoPascalThissectiongivesabriefintroductiontoTurboPascal.
1.8.1ConstantDeclarationsPascal uses the const keyword to defined constant numeric values. Thefollowing examples show constant declarations for π and the speed of light(whichis3×108).
InPascalthecaseofthecharactersisignoredbut,asamatterofprogrammingstyle,thedefinitionofconstants,suchasπ,isgiveninuppercasecharacters.
1.8.2StructureNormally programs are split into a number of sub-tasks named procedures orfunctions. These are clearly distinctive pieces of code that perform particularoperations. The main program is the basic routine to control the flow of aprogramandcallsothersub-functions.PascalProgram1.1isasimpleprogramwhichusesthewritelnprocedureto
display the text ‘Essence of Software’. The writeln procedure is a standardprocedurewhichisusedtooutputtexttothedisplay.Thestatement terminator(;) isused toenda lineofcode(orstatement)and
thekeywordsbegin and enddefine thebeginning and endof a blockof code.Commentsareinsertedintotheprogrambetweenastartcommentidentifier(/*)andanendidentifier(*/).AllPascalprogramshaveamainprogramwhichdefinestheentrypointinto
theprogramand,bymeansofcallingfunctionsandprocedures,controlsgeneralprogramflow.Inmostcasesitisbelocatedattheendofthesourcecodefile.
Figure1.9showsthebasicstructureofaPascalprogram.Eachprogramhasaprogram header which is defined with the program keyword. After this the
programvariablesaredeclared.Inthiscasethevariablesdeclaredarevar1,var2(whichareintegers)andvar3,var4(whicharerealvalues).Themainprogramisdefined after the variable declaration and can be identified between thebeginandendkeywords.Thefinalendkeywordhasafull-stopafterit.
FIGURE1.9 Pascalprogramstructure
1.8.3DataTypesVariableswithin aprogramcanbe stored as eithernumbersor characters.Forexample, the resistance of a copperwirewould be stored as a number (a realvalue) and the name of a component (such as, ‘R1’) would be stored ascharacters.Table1.3givesthefourbasicdatatypeswhichdefinetheformatofvariables.
Table1.3BasicPascaldatatypes
Type Usage Range
char singlecharacter‘a’,‘1’,andsoon Characterrange
integer signedinteger −32768to32767
real single-precisionfloatingpoint 2.9×1939to1.7×1038
boolean booleantype trueorfalse
OtherdatatypesusedinTurboPascalinclude:
An integer is any value without a decimal point; its range depends on thenumberofbytesusedtostoreit.Afloatingpointvalueisanynumberandcanincludeadecimalpoint;thisvalueisalwaysinasignedformat.Again,therangedependsonthenumberofbytesused.The integer type uses 2 bytes in memory. This gives ranges of –32768 to
32767 (a 2-byte int) and–2147483648 to 2 147483647 (a 4-bytelongint),respectively.
1.8.4DeclarationOfVariablesAprogramusesvariablestostoredata.Beforetheprogramcanuseavariable,itsnameanditsdatatypemustfirstbedeclared.Acommagroupsvariablesofthesamedatatype.Forexample,ifaprogramrequiresintegervariablesnum_stepsand bit_mask, floating point variables resistor1 and resistor2, and twocharacter variables char1 and char2, then the following declarations can bemade:
Pascal Program 1.2 is a simple program that determines the equivalentresistanceoftworesistorsof1000Ωand500Ωconnectedinparallel.Itcontainsthree floating point declarations for the variables resistor1, resistor2 andeq_resistance.
1.8.5KeywordsTurbo Pascal has 52 reserved keywords; these cannot be used as programidentifiersandcanbeinupper-orlowercase.Largeprogramscanbebuiltfromthesesimplebuildingblocks.Thefollowinggivesalistofthekeywords.
Functions and procedures are sections of code that perform a specifiedoperation.Theyreceivesomeinputandproduceanoutputinawaydictatedbytheirfunctionality.Thesecanbestandardizedfunctionswhichare inserted intolibrariesorarewrittenbytheprogrammer.TurboPascaldefinessomestandardfunctions which provide basic input/output to/from the keyboard and display,mathematical functions, character handling, and so on. They are groupedtogether into library files and are not an intrinsic part of the language. Theselibrarieslinkintoaprogramtoproduceanexecutableprogram.
1.9Exercises1.9.1.DeterminetheerrorsintheCPrograms1.4to1.6orthePascalPrograms
1.3to1.5.Eachprogramhasasingleerror.Enterthemintothecompilerandaftertheerrorhasbeencorrected,runthem.
Worksheet1:W1.1.Whichprogramminglanguageisyourchoiceforsoftwaredevelopment
(tickone):
c []
TurboPascal []
MixtureofCandPascal []
W1.2.Ifyouarerunningthecompileroverthenetworkthenwhatisyourloginname:
W1.3.LocateandrunPascalorCcompiler:
W1.4.EntereitherCProgram1.1orPascalProgram1.1andsavethistoafileonfloppydiskasPROG1_1.PAS(forthePascalfile)orPROG1_1.C(fortheCfile).
W1.5.Compiletheprogramandnoteanymessagesthatthecompilergives.
W1.6.Ifthereareerrorsintheprogramthencomparetheenteredfilewiththeprogramlistingandtrytoidentifyhowtheydiffer.Thecompilershouldidentifythelocationoftheerror(notelookalsoatthelinebefore).Thenrecompile.
W1.7.Aftertheprogramhasbeensuccessfullycompiled,runtheprogramanddetermineitsoutput.
W1.8.EntereitherCProgram1.2orPascalProgram1.2andsavefileonfloppydiskasPROG1_2.PAS(forthePascalfile)orPROG1_2.C(fortheCfile).
W1.9.UsingCProgram1.2orPascalProgram1.2determinetheequivalentresistancefortwoparallelresistors.UsethisprogramandbychangingtheresistorvaluescompleteTableW1.1.
TableW1.1Equivalentresistance
Resistor1(Ω) Resistor2(Ω) Equivalentresistance(Ω)
1000 1000
25 100
1e6(1MΩ) 1e6
150 50
2
Input/Output
2.1Introduction
Everyprogramhassomeformofoutputandnormallyaninput.Figure2.1showssomeexamplesofinputandoutputdevices.Theinputcouldbefromakeyboard,afile,input/outputports,amouse,andsoon.Outputcanbesenttodevicessuchas displays, printers, hard-disks, and so on. Typically, engineers alsocommunicate with devices such as ADC/DACs, LEDs, interface adapters, ICprogrammers,andsoon.
FIGURE2.1 Input/outputdevices
The default input device is normal from a keyboard and the default outputfromadisplay.Mostprogramsprompttheusertoenterdatafromthekeyboard.Thisdataisthenprocessedandtheresultsdisplayedtothescreen.Theusercanthenenternewdataandsothecyclecontinues.Mostoperating systemsalsoallowsa redirectionof the inputoroutput.For
example,atextfilecanactasaninputtoaprogramandtheprinterastheoutput.
2.2Pascalinput/outputComparedwithC,Pascalhasavery limitedsetof input/outputstatements(forthis reason this chapter contains many more pages on the C input/outputstatements).Pascalusesthekeyboardasthestandardinputandthedisplayasthestandard output. The two statements which are used to control this input andoutputarereadandwrite.
2.2.1WritelnThestatementsusedtooutputdatafromaprogramtothescreenarewritelnandwrite.Thewritestatementdoesnotmovethecursortoanewlineoncethedatahasbeenprinted,whereasthewritelnwill.Thestandardformatis:
Atextstringisenclosedwithinquotes(’‘)andcanbeprintedatanyplaceinthewritestatement.Valueswillbeprintedinaformatdefinedbytheirtype.Forexample an integerwill be displayedwithout a decimal point, a very large orsmall real valuewill be displayed in exponent form.The actual format of thevaluetobeprintedcanbemodifiedusingthecolonmodifier,thestandardformatis:
2.2.2ReadInThestatementsusedtoinputdataintoaprogramfromthekeyboardarereadandreadln.Thereadstatementdoesnotmovethecursortoanewlineoncethedatahasbeenentered,whereasthereadlnwill.Thestandardformatis:
Pascal Program 2.1 shows a simple example of a program which usesinput/outputstatements
2.3Cinput/outputThestandard input/output(I/O)functions inCarenot intrinsic(built-in) to thelanguage, but are stored in libraries that are linked into the program. The#includepreprocessordirectiveincludestheheaderfilesassociatedwiththem.Input/Outputfunctionsusestdio.h.Inordertoallowallpartsofthesourcecodeaccess to the functions defined in the header file the preprocessor directive islocatednearthetopofthefileinwhichitisused.Thecompilerwilltheninitiateextra error checking whenever any of the standard I/O functions are used. CProgram2.1showsaprogramwhichincludesthefilestdio.h.
2.3.1CStandardOutput(Printf(),Puts()AndPutchar())TherearethreebasicoutputfunctionsinC,theseare:
The printf() function sends a formatted string to the standard output (thedisplay). This string can display formatted variables and special controlcharacters, such as new lines (‘\n’), backspaces (‘\b’) and tabspaces (‘\t’);thesearelistedinTable2.1.
Table2.1Specialcontrol(orescapesequence)characters
The puts() function writes a string of text to the standard output and no
formatted variables can be used. At the end of the text, a new line isautomaticallyappended.The parameters passed into printf() are known as arguments; these are
separatedcommas.CProgram2.1containsaprintf()statementwithonlyoneargument,thatis,atextstring.Thisstringisreferredtoasthemessagestringandis always the first argument of printf(). It can contain special controlcharactersand/orparameterconversioncontrolcharacters.Conversioncontrolcharactersdescribetheformatofhowthemessagestring
usestheotherarguments.Ifprintf()containsmorethanoneargumentthentheformatoftheoutputisdefinedusingapercent(%)characterfollowedbyaformatdescriptioncharacter.Asignedintegerusesthe%dconversioncontrolcharacters,an unsigned integer %u. A floating point value uses the %f conversion controlcharacters,whilescientificnotationuses%e.Table2.2liststhemainconversioncontrolcharacters.
Table2.2Conversioncontrolcharacters
Figure2.2showsanexampleoftheprintf()statementwithfourarguments.Thefirstargumentisthemessagestringfollowedbytheparameterstobeprintedinthemessagestring.Inthiscasetheparametersareval1,val2andch;val1isformattedinthemessagestringasafloatingpoint(%f),val2asaninteger(%d)andchasacharacter(%c).Finally,anewlinecharacter(‘\n’)isusedtoforceanewlineontheoutput.
FIGURE2.2 Anexampleprintf()statement
A numerical value is output to a given specification using a precisionspecifier.Thisspecifiesthenumberofcharactersusedtodisplaythevalueandthenumberofplaces after thedecimalpoint.Thegeneral formatof a floatingpointvalueis:
wheremisthewidthofthevalue(thenumberofdigitsincludingthedecimalpoint),nisthenumberofdigitsfollowingthedecimalpoint,andXistheformattype(fforfloat).Thegeneralformatofastringorintegeris:
whereXistheformattype(cforcharacter,sforstringordforinteger)andmisthewidthoftheoutput.Table2.3givesafewexamples.
Table2.3Exampleofconversioncontrolmodifiers
Format Function
%.3f formatfloatingpointvaluewith3decimalplacesandadefaultwidth
%8.3f formatfloatingpointwith8reservedspacesand3placesafterthedecimalpointsuchas32.453
%10d formatintegerfor10reservedspacessuchas23
%3o formatoctalintegernumberfor3hexadecimalcharacters
%10.6e formatexponentformatwith6decimalplaces
2.3.2CStandardInput(Scanf(),Gets()AndGetchar())Thekeyboard isnormally the standard input to aprogram.Aswith theoutputfunctions, the input functions are not part of the standard language and arecontainedinastandardClibrary.Definitions(orprototypes)ofthesefunctionsare found in the header file stdio.h. By including this header file a degree oferror checking is initiated at compilation. The compiler checks, among otherthings,thedatatypesoftheparameterspassedintothefunctions.Itisthuslesslikelythattherewillbeanyrun-timeerrors.Therearethreemaininputfunctions,theseare:
If a numeric or a character variable is used with the scanf() function anampersand(&)precedeseachparameterintheargumentlist(thereareexceptionsandthesewillbediscussedinChapters6and7).Thisprefixcausesthememoryaddressofthevariabletobeusedasaparameterandnotthevalue.Thisallowsscanf()tochangethevalueofthevariable(thiswillalsobeexplainedinmoredetailinChapter6).Fornow,itshouldbeassumedthatanampersandprecedesallsimplenumericalandcharacterdatatypeswhenusingscanf().Thegeneralformatofthescanf()functionisscanf(format,&arg1,&arg2…).The first argument format is a string that defines the format of all entered
values.Forexample,“%f%d”specifiesthatarg1isenteredasafloatandarg2asaninteger.Thisstringshouldonlycontain theconversioncontrolcharacterssuch as %d, %f, %c, %s, etc., separated by spaces. Figure 2.3 shows anexampleofthescanf()functionreadingafloat,anintegerandacharacterintothevariablesval1,val2andch.
FIGURE2.3 Anexampleofthescanf()statement
Thegets(str)functionreadsanumberofcharactersintoavariable(inthiscase str); these characters are read until the ENTER key is pressed. Thegetchar() function reads a single character from the input. This character isreturnedviathefunctionheaderandnotthroughtheargumentlist.
2.4ExamplesThis section contains some practical electronics-related examples of C andPascalprograms.EachofthetestrunsrelatetoarunoftheCprogram(althoughmostofthePascaltestrunsarealmostidentical).
2.4.1FahrenheitToCentigradeConversionTemperature is typically measured in either centigrade or Fahrenheit. TheconversionfromFahrenheittocentigradeis:Program 2.2 converts from an entered value of Fahrenheit (faren) into
centigrade(cent),andTestrun2.1showsasamplerunforanenteredvalueof80°F.Theresultantvalueisdisplayedwith8placesreservedfortheanswerand2decimalplaces.ThisisspecifiedinCas%8.2fandinPascalwith:8:2afterthevariable.
wheremisthegradientofthelineandcisthepointatwhichthelinecutsthey-axis. If two points on the line are known, (x1,y1) and (x2,y2) thenm can becalculatedby:andthecvaluecanbecalculatedfrom:
Program 2.3 determines the gradient of a straight line for entered value ofx1,y1 and x2,y2 (Note that the solution of the value for c will be left as anexercise).Testrun2.2isasampletestrun.
2.4.3ForceOfAttractionThegravitationalforcebetweentwoobjectsofmassm1andm2ofadistancedapartisgivenby:where G is a gravitation constant and is equal to 6.67×10−11 m3.kg_1sec−2.
Program2.4determinesthegravitationforceandTestrun2.3showsatestrunfor the gravitation force between an apple and the earth.The parameters used
are:
The resultant gravitation force is 0.99N,which is similar to the calculationusing:
The gravitation force constant (G) has been defined, inC,with the#definestatementand,inPascal,withaconst.
2.4.4CapacitiveReactanceThe reactance of a capacitor depends upon the applied frequency. At lowfrequenciesthereactanceisextremelyhighandathighfrequenciesitislow.Thereactance(Xc)ofacapacitor,ofcapacitanceC(Farads),atanappliedfrequencyf(Hertz)isbegivenby:Figure 2.4 shows a schematic of this arrangement. There is one output
variable(Xc),twoinputvariables(fandC)andasingleconstant(π).Program2.5shows a sample program and test run 2.4 is a sample run. In C a constant isdeclared with the #define preprocessor option and Pascal uses the constkeyword.
FIGURE2.4 Capacitorconnectedtosinusoidalvoltagesource
2.4.5ImpedanceOfAnRLSeriesCircuitThemagnitudeoftheimpedanceofanRLseriescircuit(modulus|Z|)isgivenbytheequation:andtheangleoftheimpedance(argument Z )isgivenby:
Figure2.5showsaschematicofanRLseriescircuit.Program2.3determinesthemagnitudeandtheangleoftheimpedanceusingenteredvaluesofresistance(R), inductance (L) and frequency (freq). In C the inverse tangent (tan−1)function is defined (or prototyped) in math.h and is named atan(), whereas,Pascal uses the arctan() function. Both these functions return the inversetangent in radians. The program converts the returned value into degrees byscalingitbyπ/180.
FIGURE2.5 RLseriescircuit
The program uses the square root function; in C this function is (sqrt())whichisprototypedinthemath.hheaderfile.Thisinclusionhelpsthecompilerchecktheformatofthevaluessenttothefunctionasitchecksthegeneralsyntaxof the function call. It also informs the compiler that the value returned is afloatingpoint(thiswillbediscussedingreaterdetailinalaterchapter).InPascalitisalsonamedsqrt().Testrun2.5isasampleoutputusingenteredvaluesR=100Ω,L=100mH
and frequency= 1 kHz.The impedance has amagnitude of 118.10Ω and anangleof32.14°.
Program2.7determinestheequivalentresistanceofthreeresistorsconnectedinparallel. Figure 2.6 gives a schematic diagram of this set-up. The resistorsconnectedareR1,R2andR3andtheequivalentinputresistanceisRequ.Testrun2.6showsarunwithvaluesof250,500and1000Ω.
FIGURE2.6 Threeresistorsconnectedinparallel
2.4.7BitOperationsProgram 2.8 relates to digital electronics and illustrates the power of C andPascalwhendealingwithlow-levelbitoperators.TheCprogramuses&,|,⁁and~bitwise operators to create AND, OR, EX-OR, NAND and NOR Booleanfunctions.Pascalusestheoperators:and,or,xorandnot.TheNANDandNORfunctionsaregeneratedbyinvertingtheANDandORoperations.TheCprogramallowstheentryofhexadecimalvaluesusingthe%xformat
descriptorinscanf()statement.Testrun2.7showsarunwithtestvalues.
Thebitpatternsused in the test runare1110001000010101 (E215h)and1100 0100 0011 0001 (C431h). To verify the program the hexadecimalequivalents of these values are operated on by the Boolean operators and theresultscheckedagainstthetestrunresults.TheANDoperationgivesthefollowing:
TheORoperationgivesthefollowing:
TheEX-ORfunctiongivesthefollowing:
The inverse of AND (NAND) will be 0011 1111 1110 1110(3FEEh); theinverseoftheOR(NOR)is0001100111001010(19CAh).Theseresultsareidenticaltotheseintestrun2.16.Thusthetesthasbeensuccessful.ThePascalProgram2.8allowstheinputofthevaluesasaninteger.Testrun
2.8showsasampletestrun.
Worksheet2W2.1.Entertwoprogramsfromthechapterandverifythattheiroutputconforms
withthesampletestruns.
W2.2.Modifyprogram2.3sothatitalsocalculatesthevalueofc.UsethisprogramtocompleteTableW2.1.
TableW2.1Straightlinescalculations
W2.3.Writeaprogramwhichcalculatesthemagnitudeofacomplexnumberofx+jy(orinanotherformx+iy)andcompleteTableW2.2(notethatthefirstrowhasbeencompleted).Themagnitudeisgivenby:
TableW2.2Magnitude
W2.4.Writeaprogramwhichcalculatestheangleofacomplexnumberofx+jy(orinanotherformx+iy)andcompleteTableW2.3.Theangleisgivenby:
TableW2.3Angle
Worksheet3W3.1.ModifytheprogramwritteninW2.4sothatitconvertstheangleto
degreeandcompleteTableW3.1.Anangleconvertedfromradianstodegreeusing:
TableW3.1Angle
W3.2.Writeaprogramwhichdeterminestheequivalentresistanceofthreeparallelresistors.UsethisprogramtocompleteTableW3.2.
TableW3.2Equivalentparallelresistance
W3.3.ModifytheprograminQuestionW3.2sothattheuserenterstheappliedvoltagetotheparallelresistorsandtheprogramdeterminesthecurrentineachoftheresistorandtheinputcurrent.UsethisprogramtocompleteTableW3.3.Notethatthecurrentineachoftheresistorsissimplytheappliedvoltagedividedbyeachoftheresistors.AsampletestisgiveninTestrun2.9.
TableW3.3Currentflow
W3.4.ModifytheprograminQuestionW3.3sothatisdisplaysthecurrentinmilliAmps(mA).NotetoconverttomAthenmultiplythevalueby1000.AsampletestisgiveninTestrun2.10.
3
SelectionStatements
3.1if…elsestatements
A decision is made with the i f statement. It logically determines whether aconditionalexpressionisTRUEorFALSE.ForaTRUE,theprogramexecutesone block of code; a FALSE causes the execution of another (if any). Thekeywordelse identifiestheFALSEblock.InC,braces({})areusedtodefinethestartandendoftheblock.InPascal,thebeginandendkeywordsareused.Relationshipoperators,include:•Greaterthan(>).•Lessthan(<).•Greaterthanorequalto(>=).•Lessthanorequalto(<=).•Equalto(inC,itis==and,inPascal,itis=).•Notequalto(inC,itis!=and,inPascalitis<>).These operations yield a TRUE or FALSE from their operation. Logical
statements (&&, | |, !) can then group these together to give the requiredfunctionality.Theseare:•AND(inC,itis&&,and,inPascalitisand);•OR(inC,itis||,and,in
Pascalitisor);•NOT(inC,itis!,and,inPascalitisnot).If the operation is not a relationship, such as bitwise or an arithmetic
operation,thenanynon-zerovalueisTRUEandazeroisFALSE.Thefollowingis an example syntax of the if statement.If the statement block has only onestatement then, inC, thebraces ({})canbeexcluded(inPascal thebeginandendcanbeexcluded).
Thefollowingisanexampleformatwithanelseextension.
It ispossibletonestif..elsestatementstogivearequiredfunctionality.Inthenextexample,statementblock1isexecutedifexpression1isTRUE.IfitisFALSE then the program checks the next expression. If this is TRUE theprogramexecutesstatementblock2,elseitchecksthenextexpression,andsoon.IfallexpressionsareFALSEthentheprogramexecutesthefinalelsestatementblock,inthiscase,statementblock4:
Figure3.1showsadiagrammaticrepresentionofthisexamplestatement.
FIGURE3.1 Structureofthecompoundifstatement
3.1.1ExamplesThissectioncontainssomeCandPascalexampleprograms.
QuadraticequationsSome electrical examples require the solution of a quadratic equation. Thestandardformis:
Thesolutionofxinthisequationisgivenby:
Thiscanyieldthreepossibletypesofresults:1.ifb2=4ac,therewillbeasinglerealroot(x=–b/2a)2.else,ifb2>4ac,
therewillbetworealroots:
3.else,therootswillbecomplex:
Program3.1determinestherootsofaquadraticequation.Inthisprogramtheif..else statement is used to determine if the roots are real, complex orsingular.Thevaluepassedtothesquare-rootfunction(sqrt())shouldbetestedtodetermineifitisnegative.Ifitis,itmaycausetheprogramtoterminateasthesquarerootofanegativenumbercannotbecalculated(itisnumericallyinvalid).Theprogrammayalsoterminateifaiszeroasthiscausesadividebyzeroerror(thetrapforthiserrorisleftasatutorialquestion).Notethat,inC,thesqrt()function isprototyped in themath.h, thus themath.h header is included in theprogram.
Threetestruns3.1,3.2and3.3testeachofthethreetypesofrootsthatoccur.InTest run3.1 the rootsof theequationare real. InTest run3.2 the rootsarecomplex,i.e.intheformx+jy.InTestrun3.3theresultisasingularroot.
Electromagnetic(EM)wavesProgram3.2usestheifstatementtodeterminetheclassificationofanEMwavegivenitswavelength.Figure3.2illustratestheEMspectrumspanningdifferentwavelengths. The classification of the wave is determined either by thefrequency or the wavelength (normally radio and microwaves are defined bytheirfrequency,whereasothertypesbytheirwavelength).Forexample,anEMwavewithawavelengthof10misclassifiedasaradiowave,awavelengthof
500nmasvisiblelightandawavelengthof50cmisinthemicrowaveregion.Testrun3.4showsasamplerun.
FIGURE3.2 EMspectrum
EMwavescanalsobe specifiedby their frequency.Program3.3allows theuser to enter the frequency of thewave, and the program then determines thewavelengthusingtheformula:wherecisthespeedoflightandfthefrequencyofthewave.
Series/parallelresistancesProgram 3.4 determines the equivalent resistance of two resistors connectedeitherinseriesorparallel.TheCprogramusesscanf()togetthetworesistancevalues and getchar() to select the circuit configuration. Problems can occurwhenusinggetchar()afterscanf()duetonew-linecharactersbeingstoredinthe keyboard buffer. The statement fflush(stdin) has been inserted into theprograminordertoclearthebufferbeforegetchar()iscalled(stdinrepresentsthe standard input device, that is, the keyboard). TheC program also uses tolower() to convert the entered circuit selection character to lowercase (this isprotoyped in thectype.h). InTurboPascal there isno lowercaseconversionsotheuppercaseequivalentisused(upcase).
3.2switchstatementThecasestatement(andswitchinC)isusedwhentherearemultipledecisiontobemade.Itisnormallyusedtoreplacetheifstatementwhentherearemanyroutesofexecutiontheprogramexecutioncantake.Thesyntaxofcase/switchisasfollows.
In Pascal, the case statement simply selects which one of the constants(const1, const2, and so on) matches the constant value. In C, the switchstatementcheckstheexpressionagainsteachoftheconstantsinsequence(theconstantmustbeanintegerorcharacterdatatype).Whenamatchisfoundthestatement(s)associatedwiththeconstantis(are)executed.Theexecutioncarriesontoallotherstatementsuntilabreak isencounteredortotheendofswitch,whichever is sooner. If thebreak is omitted, the execution continues until theendofswitch.If none of the constantsmatches the switch expression a set of statements
associatedwiththedefaultcondition(default:)isexecuted.
3.2.1ExamplesResistorcolourcodeResistorsarenormallyidentifiedbymeansofacolourcodesystem,asoutlinedinTable3.1.Program3.5usesacase/switchstatementtodeterminethecolourofaresistorbandforanenteredvalue.
Table3.1Resistorcolourcodingsystem
Testrun3.6showsasamplerun.
Program 3.6 uses #define directives to define each of the resistor colourbands.Theremaybeaclashwiththesedefinesifotherheaderfilescontainthesedefinitions.IfthisoccurschangethedefinestoRES_BLACK,RES_BROWN,etc.Adefault:hasbeenaddedtocatchanyinvalidinput(suchaslessthan0or
greaterthan9).
ResistanceofaconductorThe resistance of a cylindrical conductor is a function of its resistivity, cross-sectional area and length. These parameters are illustrated in Figure 3.3. Theresistanceisgivenby:
FIGURE3.3 Cylindricalconductor
whereρ=resistivityoftheconductor(Ω.m);l=lengthoftheconductor(m);A=cross-sectionalareaoftheconductor(m2).Program3.7determines the resistanceofacylindricalconductormade from
either silver, manganese, aluminium or copper. The resistivities of thesematerialshavebeendefinedusing#definemacros(inC)orconst(inPascal).The user enters the conductor type as a character (‘c’, ‘a’, ‘s’ or ‘m’)
which can either be in upper or lowercase format as the tolower() functionconverts theenteredcharacter to lowercase (this isprotyped inctype.h).Whenan invalid character is entered the default condition of the case statement isexecuted,andthetextInvalidoptionisdisplayed.Theprogramthencallstheexit()function;theargumentpassedtothisfunctionistheterminationstatus.Avalueof0describesanormaltermination;anyothervaluesignalsanabnormalprogramtermination.InC,theprintf()statementdisplaystheresistanceinscientificformat(%e)
asvaluesaretypicallymuchlessthan1Ω(suchasmΩorμΩ).
Testrun3.7usesanaluminiumconductorwitharadiusof1mmandlength1000m.Theresistanceisfoundtobe8.08Ω.
ThePascalProgram3.7showsthatseveralconstantsforasinglecaseoptioncan be used (for example, ‘a’, ‘A’). In C, it is possible to have several case
optionsintheswitchstatement.Forexample,ifthetolower()functionisnotusedinprogram3.7thenthecaseoptioncanbemodifiedsothatitincludestheupperandlowercaseoptions,asshowninthefollowingcode:
3.3Exercises3.3.1.ModifyProgram3.1sothatitcannotgenerateadividebyzeroerror,that
is,whenais0(zero).Notethatifais0thentherootwillbe–c/b.3.3.2.ModifyProgram3.2sothattheusercanentertheEMwaveasafrequency
orawavelength.Asamplerunisshownintestrun3.8.
3.3.3.ModifyProgram3.2soitusesthe#definestatementtodefinelimitsforthewavelength,forexample:
3.3.4.Capacitanceisnormallydefinedasavalueandaspecifiedunit,suchaspF,nF,μF,mForF.WriteaprograminwhichacapacitancevalueandtheunitareenteredandtheprogramdisplaystheactualnumericalvalueinFarads.Thecapacitanceunitshouldbeenteredasacharacter.AsampletestrunisgiveninTestrun3.9.NotethatpFis10−12F,pFis10−9F,μFis10−6FandmFis10−6F.
3.3.5.RepeatQ3.10forthevalueoftheresistance.TheunitsenteredareeithermΩ(‘m’),Ω(‘1’),kΩ(‘k’)orMΩ(‘M’).Testrun3.11showsasamplerun.NotethatmΩis10−3Ω,kΩis103Ωand?Ωis106Ω.
Worksheet4:W4.1.EnterProgram3.1anduseittocompleteTableW4.1
TableW4.1Rootsofaquadraticequation
Equation Root(s)
x2+21x–72=0
5×2+2x+1=0
25×2–30x+9=0
6×2+9x–20=0
W4.2.ModifyProgram3.1sothatitcannotgenerateadividebyzeroerror,thatis,whenais0(zero).Notethatifais0thentherootwillbe-c/b.
TableW4.2Rootofaquadraticequation
Equation Root
0×2+4x–2=0
0×2+6x+6=0
W4.3.Writeaprograminwhichtheuserentersavalueofresistanceandtheprogramdisplaystheresistancevalueinthebestpossibleunits.A
possibleimplementationcouldbe:Iftheresistanceislessthan1000Ω(1e3)thenitisprintedasthevalueinohms;else,ifitisbetween1000(le3)and1000000Ω(1e6)thenthevalueisprintedaskΩ;else,ifitisgreaterthan1000000(1e6)thenitisprintedinMΩ.
TestrunW4.1showssomesampleruns.
Worksheet5:W5.1.OPTIONAL.EnterProgram3.5andtesttheresults.W5.2.Writeaprogramusingthecase(orswitch)statementthatallowstheuser
toselectfromamenuofoptions.Theseoptionsallowtheusertoselecteitherthecalculationoftheequivalentresistanceoftwoseriesortwoparallelresistors.Theusershouldentera1iftheseriesequivalentisrequiredora2ifparallelrequired.SamplerunW5.1showsasampletestrun.
W5.3.ThetextbackgroundfunctionallowsthecolourofthebackgroundtobechangedtoBLACK,BROWN,RED,…andclrscrclearsthescreen.Sampleprogram3.8showsanexampleprogramoftheiruse.Writeaprogramwhichallowstheusertoenteracolourandthethenprogramchangesthebackgroundcolour.TableW5.1showsthecolourdefinitions.
TableW5.1
OPTIONALEXERCISE:W5.4.ModifytheprogramwritteninW5.2sothattheuserentersan‘s’for
seriesresistanceanda‘p’forparallel.SamplerunW5.2showsasample
4
RepetitiveStatements
4.1Introduction
Iterative,orrepetition,allowstheloopingofasetofstatements.Therearethreeformsofiteration:
4.2forManytaskswithinaprogramarerepetitive,suchaspromptingfordata,countingvalues, and soon.Thefor loopallows theexecutionofablockofcode foragivencontrolfunctionoragivennumberoftimes.InPascaltheformatis:
Inthiscase,valuestartsatstartvalandendsatendval.Eachtimeroundtheloop,valuewillbeincrementedby1.Ifthereisonlyonestatementintheblockthenthebeginandendreservedwordscanbeomitted.InCtheformatis:
where:
4.3Examples4.3.1ASCIICharactersProgram4.1DisplaysASCIICharactersForEnteredStartAndEndDecimalValues.TestRun4.1DisplaysTheASCIICharactersFromDecimal40(‘(‘)To50(‘2’).
4.3.2TransientResponseOfAnRCCircuitFigure4.1 illustratesanRCcircuitwithavoltage stepappliedat t=0.Whenavoltage step, amplitude E volts, is applied to this circuit it produces anexponentialcurrent.
FIGURE4.1 RCcircuitwithstepinputappliedatt=0
Thefollowingdefinesthetransientcurrentinthecircuit.
andthevoltageacrosstheresistorwillbe:
Program4.3determinesthevoltageacrosstheresistoratgiventimeintervals.Theuserenterstheendtimeandthenumberoftimestepsrequired;theprogramdeterminesthevoltageateachofthetimesteps.
Testrun4.2showsthatthevoltageacrosstheresistorstartsatamaximumatt=0. This is because the voltage across the capacitor is initially zero. As thecapacitor charges, the voltage across itwill increase until it almost equals theappliedvoltage.Thecurrentinthecircuitwillalsobeatamaximumwhenthestepisapplied.Itwillthendecaytoalmostzeroataratedeterminedbythetimeconstant(whichisaproductofRandC).
4.3.3BooleanLogicProgram4.3isanexampleofhowaBooleanlogicfunctioncanbeanalyzedanda truth table generated. The for loop generates all the required binarypermutationsforatruthtable.TheBooleanfunctionusedis:A schematic of this equation is given in Figure 4.2. Test run 4.3 shows a
samplerun.
FIGURE4.2 Digitalcircuit
4.4Exercises4.4.1.Writeaprogramwhichprintsallthecharactersfrom‘0’(zero)to‘z’in
sequenceusingaforloop.4.4.2.Writeaprogramwhichdisplaysthesquares,cubesandfourthpowersof
thefirst15integers.Asampleoutputisgivennext.
4.4.3.Writeaprogramwhichdisplaystheyvaluesintheformulasgivenbelowandwiththegivenxsteps.
Asamplerunofthefirstequationisgivennext.
4.4.4.Writeaprogramwhichdisplaysthesineofanumberfrom0°degreesto90°instepsof10°.
4.4.5.ModifyProgram4.3sothatitdeterminesthetruthtableforthefollowingBooleanequation:
Table4.1
Truthtable
4.4.6.WriteaprogramwhichwilldeterminetheimpedanceofanRLseriescircuit.Theprogrammustcalculatethemagnitudeoftheimpedance.
Worksheet6:W6.1.EnterProgram4.1anduseittocompleteTableW6.1.
TableW6.1ASCIIcharacters
Value Character
34
35
36
37
38
64
65
66
67
68
69
70
W6.2.Writeaprogramwhichliststhesquareofthevaluesfrom1to10.AsampleruninshowninTestrunW6.1.
W6.3.CompleteeitherExercise4.4.3(i),Exercise4.4.4orExercise4.4.5.
4.5while()The while statement allows a block of code to be executedwhile a specifiedcondition is TRUE. It checks the condition at the start of the block; if this isTRUEtheblockisexecuted,elseitwillexittheloop.Thesyntaxis
If the statement block contains a single statement then the braces may beomitted(althoughitdoesnoharmtokeepthem).Afewexamplesare:
4.6repeat..until()anddo..while()InCthedo..while()statementissimilarinitsoperationtowhile()exceptthatit tests the condition at the bottomof the loop.The repeat..until() inPascal isalsosimilar tothewhile()statementbutunlikewhile() theloopquitswhentheassociated condition is true. These loops thus allow statement block to beexecutedatleastonce.Thesyntaxis:
Aswithfor andwhile loops thebracesareoptional.Thedo..while() andrepeat..until()loopsrequireasemicolonattheendoftheloop,whereasthewhile()doesnot.
4.7Examples4.7.1RepeatingProgramOftenAUserIsAskedToRepeatTheProgramOnceItHasFinishedCalculatingValues.ThisIsSometimesDoneByAskingTheUserIfTheyWantToRepeat(OrContinue)TheProgram.IfTheUserEntersA‘Y’CharacterThenTheProgramIsRepeated,ElseA‘N’CharacterWillExitTheProgram.Program4.4ImplementsThisWithARepeat..Until()/Do..While()Loop.
4.7.2LimitingRangesOfInputsMost of the values that are entered into a program have a certain range. Forexampleifauserisaskedentertheiragethenthevaluewillalwaysbe:•Aninteger.•Apositivevalue.•Lessthan130.Ifauserentersaninvalidvaluethentheprogramcouldeither:•Crash,whichtypicallyhappenswhenaprogramtriestodividebyzeroor
determinesthesquarerootofanegativenumber.•Givesinvalidresults.Thus it is important that theuser is stopped fromenteringvalueswhichare
invalid. Program 4.5 allows the user to determine the equivalent parallelresistance for two resistors in parallel. The range of value values of enteredresistanceisbetween0Ωand1MΩ.Therepeat..until()/dowhile()loopisplacedaroundtheuserentryofeachofthevalues.Theseloopscontinueuntilauserentersavalidvalue.Testrun4.4showsasamplerun.
Program4.6givesanexampleofthedeterminationofaccelerationgivingtheinitialandendvelocity,andthetimedifference.Therangeofvelocityvaluesisbetween0and1000m/s,and the rangeof timedifferencevalues isbetween0and60s.Testrun4.5showsasamplerun.
(viii)
(ix)
4.8.5.WriteaProgramtoconvertadecimalnumbertooctal(base8).AsamplerunisgiveninTestrun4.6.
4.8.6.Replacethefollowingforloopwitharepeat..untilandwithawhile..dointheexamplesbelow.(i)
(ii)
(iii)
4.8.7.Writeaprogramtoconverthexadecimaltodecimal.AsamplerunisshowninTestrun4.7.
4.8.8.Thedraincurrent,inmilliamps,ofasampledepletion-typeFETisgiven
by:
Writeaprogramwhichdeterminesthedraincurrent(inmA)forgate-sourcevoltages(VGS)from–5to5Vinstepsof0.5V.AsamplerunisgiveninTestrun4.8.
Worksheet7:W7.1.Modifyaprogramfromapreviousworksheetsothatitpromptstheuser
toiftheywanttorepeattheprogram.W7.2.Writeaprogramwhichwillcalculatetheequivalentresistanceofthree
resistorsinparallel.Iftheuserentersaninvalidvalue(suchasanegativevalue)theprogramwillprompttheusertoenteravalidinput.AsamplerunisshowninTestrunW7.1.
W7.3.Writeaprogramwhichwillconvertdecimalvaluetohexadecimal(base16).AsamplerunisshowninTestrunW7.2.
W7.4.WriteaPrograminwhichyouenterthenumberofbitsinabinarynumber,enterthesebitsandthencalculatethedecimalequivalent.AsamplerunisgivenintestrunW7.3.Notethatthevalidinputforthebitsshouldbeonlya0ora1.
5
Functions
5.1Introduction
Functions are identifiable pieces of code with a defined interface. They arecalledfromanypartofaprogramandallowlargeprogramstobesplitintomoremanageabletasks,eachofwhichcanbeindependentlytested.Functionsarealsousefulinbuildinglibrariesofroutinesthatotherprogramsuse.Severalstandardlibrariesexist,suchasamathsandinput/outputlibraries.Afunctioncanbethoughtofasa‘blackbox’withasetofinputsandoutputs.
It processes the inputs in a way dictated by its function and provides someoutput. Inmostcases theactualoperationof the ‘blackbox’ is invisible to therest of the program.Amodular program consists of a number of ‘black box’working independently of all others, of which each uses variables declaredwithin it (localvariables)andanyparameterssent to it.Figure5.1 illustratesafunctionrepresentedbyanideal‘black-box’withinputsandoutputs,andFigure5.2showsamainfunctioncallingseveralsub-functions(ormodules).
FIGURE5.2 Hierarchicaldecompositionofaprogram
5.2ArgumentsandparametersThedata typesandnamesofparameterspassed intoa functionaredeclared inthe function header (its interface) and the actual values sent are referred to asarguments.Theycanbepassedeitherasvalues(knownas‘passingbyvalue’)oraspointers(knownas‘passingbyreference’).Passingbyvalueinvolvessendingacopyofitintothefunction.Itisnotpossibletochangethevalueofavariableusing this method. Variables can only be modified if they are passed byreference (thiswill be covered in thenext chapter).This chapter looksathowparameterspassintoafunctionandhowasinglevalueisreturned.Anargumentandaparameteraredefinedasfollows:
An‘argument’istheactualvaluepassedtoafunction.
A‘parameter’isthevariabledefinedinthefunctionheader.
5.3CfunctionsFigure 5.3 shows a program with two functions, main() and functionl().Functionmain()callsfunctionl()andpassesthreeparameterstoit; thesearepassedasvalues.Acopyofthecontentsofdgoesintog,eintohandfintoi.
FIGURE5.3 Localandglobalvariables
Variablesdeclaredwithina functionaredescribedas localvariables.Figure5.3showsthatd,eandfarelocalvariableswithinmain();g,h,i,jandkarelocal within function1(). These will have no links to variables of the samenamedeclaredinotherfunctions.Localvariablesonlyexistwithinafunctioninwhichtheyaredeclaredanddonotexistoncetheprogramleavesthefunction.Variablesdeclaredat the topof the source file (andnotwithin a function) aredefined as global variables. These allow functions, within the source file, toaccessthem.Caremustbetakenwhenusingglobalvariablesformanyreasons,one of which is that they tend to lead to programs that are unstructured and
difficulttomaintain.InFigure5.3thefunctionfunction1()makesuseofthevariableaasthisis
declaredasaglobalvariable.Thisfunctioncannotbemodelledasa‘blackbox’as it can modify a variable which is not passed to it. In a relatively smallprogramthismaynotcreateaproblembutasthesizeoftheprogramincreasesthecontrolofvariablescanbecomedifficult.Figure 5.4 shows an example of how things can go wrong with global
variables.Inthisexample,aglobalvariableiisusedbytwofunctions.Initially,thevalueofiwithintheloopinmain()willbe0.Thefunction1()functioniscalledwithinthisloop,whichusesthevariableiwithinanotherloop.Eachtimeit is incremented theglobalvariable takeson the incrementedvalue.Whentheprogramleavesthisfunctionthevalueofiwillhavechanged(thatis,itwillbe10). This causes the for() loop in main() to end. If the variable i had beendeclared locallywithin bothmain() andfunction1() this problemwould nothaveoccurred.Asarule,calledmodulesshouldbeself-containedanduseonlytheparameterssenttothem.
FIGURE5.4 Anexampleoftheuseofglobalvariables
Program5.1containsafunctionnamedprint_values().Thisiscalledfrommain() and variables a and b are passed into the parameters c and d,respectively;canddarelocalparametersandonlyexistwithinprint_values().Thevaluesofcanddcanbechangedwithnoeffectonthevaluesofaandb.
5.3.1ReturnValueThe return statement returns a single value from a function to the callingroutine.Programsinpreviouschaptershaveusedfunctionsthatreturnvalues.Iftherearenoreturnstatementsinafunctiontheexecutionreturnsautomaticallytothe calling routine upon execution of the closing brace (i.e. after the finalstatementwithin the function). Program5.2 contains functionswhichwill addandmultiplytwonumbers.Thefunctionaddition()usesreturn tosendbacktheadditionofthetwovaluestothemain().
Figure 5.5 shows a simple structure chart of this program. The functionaddition()iscalledfirst;thevariablessentareaandbandthereturnvalueisput into the variablesummation.Next, themultiply() is called; the variablessentarealsoaandbandthevaluereturnedgoesintomulti.Finally,thefunctionprint_values()iscalled;thevaluessentarea,b,multiandsummation.
FIGURE5.5 Basicstructurechartforprogram5.2
A function can have several return points, although it is normally better tohaveonlyonereturnpoint.Thisisnormallyachievedbyrestructuringthecode.An example of a function with two returns is shown next. In this example adecisionismadeastowhetherthevaluepassedintothefunctionispositiveornegative. If it isgreater thanor equal to zero it returns the samevalue, else itreturnsanegativevalue(return(-value)).
5.3.2FunctionTypeProgram 5.2 contains functions that return integer data types. It is possible toreturn any other of C’s data types, including float, double and char, byinsertingthedatatypebeforethefunctionname.Ifnodatatypeisgiventhenthedefaultreturntypeisint.Thefollowinggivesthegeneralsyntaxofafunction.
Cisaflexiblelanguageinitsstructure.Itallowsthearrangementoffunctionsinanyorderandevenwithindifferentfiles.Ifthecompilerfindsafunctionthathasnotbeendefined(orprototyped)thenitassumesthereturntypewillbeint.It also assumes that at the linking stage the linker will be able to find therequired functioneither in thecurrent compiledprogram, the librariesorotherobject codes. It is thus important that the function return data type is definedwhen thecompiler is compiling the function;otherwise itwill assume that thereturntypeisint.Functiondeclarations(orprototypes)arenormallyinsertedeitheratthetopof
each file, locally within a function, or in a header file (the .h files). Thesedeclarationsallowthecompilertodeterminethereturntypeandthedatatypesofall parameters passed to the function. It thus allows the compiler to test forillegal data types passed to a function in error. For example the following areinvalid uses of the function printf (), sqrt() and scanf(). The printf() has anincorrectsyntaxasthefirstargumentshouldbeaformatstatement(i.e.astring),the sqrt() function should be passed a floating point value and the scanf()functionrequiresaformatstringasthefirstargument.
Ifthestdio.hheaderisnotincludedthecompilerdoesnotgenerateanyerrorsfortheincorrectusageofprintf()andscanf().Thesameappliestothemath.hheaderfileandthefunctionsqrt().When a function prototype is inserted at the top of the file it is a global
declaration of that function within the source code file. Otherwise, thedeclarationcanbe inserted into thevariabledeclaration listswithina function;thiswillmakethedefinitionlocalonlytothefunctioninwhichitisdefined.Ifafunctiondoesnotreturnavaluethenthedatatypedefinitionforthereturn
value should bevoid.Also, if no parameters are sent to the function then theargumentlistcontainsavoid.Thecompilerwouldthusflaganerrororwarning
if any parameters are passed to a function with a void argument list or if areturnedvalueisusedfromavoidreturndatatype.Figure5.6showstheoperationofafunctionprototype.Atthetopofthefile
theprototypedeclarestheparametertypesoftheargumentspassed(inthiscase,twofloats)andthereturndatatype(inthiscasefloat).Thecompilerchecksallarguments sent to this function to see if they match up with these types. Awarning or error is generated if there is a mismatch. The return type is alsochecked.
FIGURE5.6 Checkingconductedbythecompileronfunctionprototypes
Program5.3containsafunctionpower()whichisprototypedatthetopoftheprogram.Thereturnvalueisdouble;thefirstargumentisdoubleandthesecondis int. This function uses logarithms to determine the value of x raised to thepowerofn.Theformulausedisderivednext;thelog()functionisthenatural
logarithm and the exp() the exponential function. Both of these require theparametersentasdoubleandthereturntypeisalsodouble.
Somecompilersgiveawarningifthereturnvaluedatatypeisdifferentfromthedatatypeofthevariabletowhichitisassigned.Forexample,ifthedatatypeofthevariablexinProgram5.3ischangedtoafloatthenitisgoodpracticetorecastthereturnvaluetoafloat,asshownnext.
5.4PascalfunctionsInPascalafunctionreturnsasinglevalue.Itisidentifiedbythefunctionheader,whichisintheform:
wheretheparametersarepassedthroughtheformal_parameter_listandtheresulttypeisdefinedbyresult_type.Program5.1containstwofunctionsnamedadditionandmultiply.Incalling
theadditionfunctionandvariablesaandbarepassedintotheparameterscandd,respectively;canddarelocalparametersandonlyexistwithinaddition().Thevaluesofcanddcanbechangedwithnoeffectonthevaluesofaandb.Thisfunctionreturnsavaluebacktothemainprogrambysettingavaluewhichisthesamenameasthefunction.Program5.1alsousesaprocedurewhich,inthiscase,issimilartoafunction
butdoesnotreturnanyvaluesbacktothecallingprogram.
Figure 5.5 shows a simple structure chart of this program, The functionaddition()iscalledfirst;thevariablessentareaandbandthereturnvalueisput into the variablesummation.Next, themultiply() is called; the variablessentarealsoaandbandthevaluereturnedgoesintomulti.Finally,thefunctionprint_values()iscalled;thevaluessentarea,b,multiandsummation.Program5.2containsfunctionsthatreturnintegerdatatypes.Itispossibleto
return anyother ofC’s data types, includingreal,double andcharacter, byinsertingthedatatypeafterthefunctionname.A function can have several return points, although it is normally better to
haveonlyonereturnpoint.Thisisnormallyachievedbyrestructuringthecode.An example of a function with two returns is shown next. In this example adecisionismadeastowhetherthevaluepassedintothefunctionispositiveornegative. If it isgreater thanor equal to zero it returns the samevalue, else itreturnsanegativevalue(mag=-val).
Program 5.2 contains a function power() which has a return data type ofdouble; the first argument is double and the second isinteger.This functionuseslogarithmstodeterminethevalueofxraisedtothepowerofn.Theformulausedisderivednext;theIn()functionisthenaturallogarithmandtheexp()theexponentialfunction.
5.5ExamplesThissectioncontainsafewsampleCandPascalprogramswhichusefunctions.
5.5.1TanFunctionThere is no tan function in Pascal; thus to overcome this Pascal Program 5.3containsatanfunctionandTestrun5.1showsasamplerun.
C,unlikePascal,hasatanfunction,thustoavoidredeclaringitCProgram5.4hasafunctioncalledtangent().Toimproveaccuracytheprogramusesdoubledatatypes.Forthisreasonthescanf()andprintf()functionsusethedatatype%Ifconversioncharacters.
5.5.2CentigradeToFahrenheitConversionPascalProgram5.4usestwofunctionstoconvertfromFahrenheittocentigrade,andviceversa.Testrun5.2showsasampletestrun.
PascalProgram5.5andCProgram5.6usesthetwofunctiondevelopedintheprevious programs to display a table of values from0°C to 100°C in steps of10°C.Testrun5.3showsasamplerun.
5.5.3CombinationalLogicIn this example, the followingBoolean equation is processed to determine itstruthtable.
Figure5.7givesaschematicrepresentationofthisBooleanfunction.
FIGURE5.7 Schematicrepresentationofthefunction
Thefournodesnumberedonthisschematicare:1.
2.A.C3.
4.
Table 5.1 gives a truth table showing the logical level at each point in theschematic.Thistableisnecessarytochecktheprogramresultsagainstexpectedresults.Table5.2givestheresultingtruthtable.
Table5.1Truthtable
Table5.2Truthtable
Thepermutationsofthetruthtableinputvariables(i.e.000,001,010,011,…,111)aregeneratedusing3nestedforloops.TheinnerlooptogglesCfroma0 to a 1, the next loop toggles B and the outer loop toggles A. The Booleanfunctionsusethelogicaloperators&&and||.Recallthattheseoperatorstreatavalueof0(zero)asFALSEandanyothervalueasTRUE.
Test run5.4 showsa sample runof theprogram.Notice that the results areidenticaltothetruthtablegeneratedbyanalyzingtheschematic.
Pascal Program 5.6 shows the equivalent Pascal program. As Pascal hasreserved keywords for AND, OR and NOT the function names have beenchangedtoreflectthenumberofinputstheyhave,suchasOR3fora3-inputORgateandAND2fora2-inputANDgate.
5.5.4ImpedanceOfASeriesRLCircuitThemagnitudeoftheimpedanceofanRLcircuitisgivenbytheequation:
andthephaseangleofthisimpedanceisgivenby:
Figure5.8givesaschematicofanRLseriescircuit.
FIGURE5.8 RLseriescircuit
Figure 5.9 gives a structure chart which outlines a basic design for thisproblem. Inputs are resistance (R), inductance (L) and frequency (f). Theprogramdeterminesthemagnitudeandphaseangleoftheimpedance.Inordertodetermine thesevalues the reactanceof the inductormustbedeterminedusingXL=2πfL.
Testrun5.5givesasamplerunofthisprogram.Theinputparametersusedareresistance1kΩ,inductance1mHandappliedfrequency1MHz.
PascalProgram5.7givestheequivalentPascalprogram.
5.6Exercises5.6.1.Writeaprogramwhichdeterminesthemagnitudeofanenteredvalue.The
programshoulduseafunctiontodeterminethis.5.6.2.Writeaprogramwhichdeterminesthemagnitudeandangleofacomplex
number(intheformx+iy,orx+jy).Theprogramshouldusefunctionstodetermineeachofthevalues.CompleteTable5.3usingtheprogram(thefirstrowhasalreadybeencompleted).
Table5.3Complexnumbercalculation
5.6.3.Writeamathematicalfunctionforafactorialcalcuation,where:
5.6.4.Writemathematicalfunctionsforthefollowing
Thesineandcosinefunctionsshouldcalculatedfromfirstprincipleswith:
Theerrorinthefunctionsshouldbelessthan1×10−6.5.6.5.UsingthefunctionsdevelopedinExercise5.6.2andthestandardsineand
cosinelibraryfunctions,writeaprogramwhichdeterminestheerrorbetweenthestandardlibraryfunctionsandthedevelopedfunctions.From
this,completeTable5.3.
Table5.3Sineandcosineresults
5.6.6.Writeamathematicalfunctionwhichdeterminestheexponentialofavalueusingthefirstprinciplesformula:
Comparetheresultwiththestandardexp()libraryfunction.5.6.7.WriteBooleanlogicfunctionsforthefollowingfourdigitalgates:
Worksheet8:W8.1.Writeaprogramwithseparatefunctionswhichdeterminethegradientof
astraightline(m)andthepointatwhichastraightlinecutthey-axis(c).Theenteredparametersaretwopointsontheline,thatis,(x1,y1)and(x2,y2).FromthisprogramcompleteTableW8.1(thefirstrowhasalreadybeencompleted).
TableW8.1Straightlinecalculations
W8.2.Writeaprogramwhichhasafunctionwhichwillonlyreturnarealvalue
whentheenteredvalueiswithinaspecifiedrange.Examplesofcallstothisfunction(which,inthiscase,isnamedget_real)aregivennext.
whichwillonlyreturnavaluefromthefunctionwhentheenteredvalueisbetween0and100.Asamplerunisgivennext.
W8.3.Modifytheprogramdevelopedanduseittoprompttheusetoenteravalueofcurrent(between0Aand10A)andvoltage(between0Vand100V).Theprogramwillthendeterminetheresistancebydividingtheenteredvoltagebytheenteredcurrent.Theprogramshouldcontaintwofunctions:get_real()andcale_current().
6
ParameterPassing
6.1Introduction
Parameterpassing involvespassing inputparameters intoamodule (a functioninC and a function and procedure in Pascal) and receiving output parametersbackfromthemodule.Forexampleaquadraticequationmodulerequiresthreeparameterstobepassedtoit,thesewouldbea,bandc.Thesearedefinedastheinputparameters.Theoutputparameterswouldbethetworootsoftheequation,such as root1 and root2. Another parameter could also be passed back toindicate the typeof root (suchas singular, realorcomplex).This indication isnormallyknownasa flag.Figure6.1 illustrates thepassingofparameters intoandoutofamodule.
FIGURE6.1 Parameterpassing
InPascalthemodulewouldbedefinedas:
InCaflagistypicallypassedbackthroughthefunctionheader,thus:
6.2PascalparameterpassingProcedures are used inPascalwhen parameters need to be passed back to thecallingroutine.Functionsarenormallyusedwhenthereisonlyonevaluepassedback,whereasaprocedurecanreturnanynumber(orevennone).Thefirstpartof defining a procedure is to define the input parameters and the outputparameters.The inputparameters aredeclared in theparameter list andoutputparametersaredefinedwithaprecedingvarkeyword.Forexample,iftheinputparametersarexandy,andtheoutputparametersarewandzthenthefollowingprocedurewouldbedefined:
Inthiscaseonlyvalueswillbepassedintothevariablesxandy,whereasthevalues of w and z will be passed back to the calling module. If a procedurerequires localvariables then thesearedeclaredafter theprocedureheader.Forexample, if the procedure in the last example has two local variables namedtemp1andtemp2thenitwillhavetheform:
Local variables only exist within the procedure and their contents are lostwhentheprocedurequits.Program6.1 shows an example programwith a procedurewhich swaps the
valuesoftwovariables.Inthiscaseatemporarylocalvalue(temp)holdsoneofthevalues(temp:=x)so that thecontentsof theothervaluecanbeplaced in it(x:=y).The temporaryvalue is thenput into theothervariable(y:=temp).Thisoperationperformsaswap.
Program6.2 calculates the gradient of a straight line given two coordinates(x1,y1)and(x2,y2).
6.3Cparameterpassing
One of the most confusion areas of C programming is the usage of pointers.TheybasicallyrefertoaddressesinmemorybuttothenovicetheyareoneoftheleastlikedelementsofCprogramming.Inmanycasestheyareextremelyusefulandallowtheprogrammertodirectlyaccessareasofmemory.
6.3.1IntroductionIfacompanyweretosendaformtoapersonandtheyneglectedtoinformtheperson of the correct return address then it would not be possible for therecipient tosendback themodified form(unless thepersonalreadyknows theaddress).Variablessenttofunctionsoperateinasimilarmanner.Ifthefunctiondoesnotknowwhereavariablelives(itsaddressinmemory)thenthefunctioncannotchangeitscontents.A program uses data which is stored by variables. These are assigned to a
unique space inmemory, the number of bytes they use depends on their datatype.Forexample,acharuses1byte,anintwill typicallytake2or4bytes,andafloat,typically,4or8bytes.Eachmemorylocationcontainsonebyteandhasauniqueaddressassociatedwithit(thatis,itsbinaryaddress).Thisaddressisnormallyspecifiedasahexadecimalvalueas thiscanbeeasilyconvertedtothe actual binary address. The memory map in Figure 6.2 shows how threevariablesvaluel,value2 and ch could be allocated inmemory. This diagramassumesthatafloatuses4bytes,andanint2bytes.Thecompiler,inthiscase,hasallocatedvaluelfromaddresses100hto103h,value2at104hand105h,andch is allocated to 106h. The start of the variable’s address inmemory can bedescribedasamemorypointertothevariable.Apointervariableisusedtostoreamemoryaddress.
FIGURE6.2 Examplememorymap
Variables sent to a function can have their contents changed by passing apointer in the argument list. Thismethod involves sending amemoryaddressratherthanacopyofthevariable’svalue.Aprecedingampersand(&)specifiesapointer.Thiscanbethoughtofasrepresentingtheaddressof:
A pointer to a variable will store the address to the first byte of the areaallocatedtothevariable.Anasterisk(*)precedingapointerisusedtoaccessthecontentsofthelocationpointedto.Thenumberofbytesaccessedwilldependonthe data type of the pointer. The * operator can be thought of representingataddress:
Figure6.3showsanexamplememorymap.Avariableresistance_1hasthevalueof310.0 and is storedatamemory locationstartingat107h. If thedatatype is a short integer then it will take up 2 bytes in memory (i.e. 107h and108h),ifitisafloatitmaytakeup4bytesinmemory(i.e.107hto110h).Thememorymapalsoshowsthatapointerptrpointstomemorylocation102h.The
valuestoredatthislocationis15;*ptraccessesitscontents.Thedeclarationofthepointerdefinesthedatatypeofthepointerandthusthenumberofbytesusedtostorethevalueattheaddresspointedtobythepointer.
FIGURE6.3 Examplememorymap
6.3.2PointersWithFunctionsIn the previous chapter it was shown that a single value is passed out of afunction through the function header. In order to pass values out through theargumentlisttheaddressofthevariableispassed;thatisreferredtoas‘callbyreference’.Todeclareapointerthedatatypeisspecifiedandthepointernameisprecededbyanasterisk.Thefollowingisthegeneralformat:
Inthiscaseptr_nameisthenameofthepointer.Thecontentsofthevariableatthisaddresscanbeaccessedusing*ptr_name.Whenafunctionistomodifyavariable thenapointer to itsaddress issent.Forexample, if thevariable tobemodifiedisvaluethentheargumentpassedis&value.Program6.1showsanexampleofa function thatswaps thecontentsof two
variables (a andb).Figure6.4 showshow thecompiler checks theparameterspassedtothefunctionandthereturntype.Thefunctionprototype,inthiscase,specifies that the parameters sent are pointers to integer values and the return
type isvoid.The compiler checks that theparameters sent to the function areinteger pointers and that nothing is assigned to the return value from thefunction.
FIGURE6.4 CompilercheckingforProgram6.1
Program6.2 calculates the gradient of a straight line given two coordinates(x1,y1)and(x2,y2).Withintheget_coord()functionthescanf()donotrequireaprecedingampersand;thevariableargumentsarealreadypointers.
An example of a standardC function that uses call by reference is scanf()whereapointer ispassedforeachvariable.Thisallowsthefunctiontochangeitscontents.
6.4Examples6.4.1QuadraticEquationsC Program 6.2 determines the roots of a quadratic equation. The functionget_values()getsvariablesa,bandc;thesevariablesarepassedaspointers.The function to determine the root(s) of a quadratic equation is
quadratic_equ().Thisreturnstheroottype(suchas,singular,realorcomplex)through the function header and passes the equation root(s) through theargumentlistusingpointers.Theroottypereturnedcanbereferredtoasareturnflag;thisflagissetupusinganenumdeclaration.Therearethreepossiblestatesforthis:SINGULAR(avalueof0),REAL_ROOTS(avalueof1)andCOMPLEX_ROOTS(avalueof2).Theprogramthenusestheflagtodeterminehowtheroot(s)aretobedisplayed.Iftherootissingularthenprint_results()printsasinglevalueofroot1;else,iftherootsarereal,thentwovaluesroot1androot2areprinted;andiftherootsarecomplexthefunctionwillprinttherootsintheformroot1
+/-jroot2.Figure6.5givesabasicstructurechartofthisprogram.Thereturnflagfrom
thequadratic_equ() function is represented by an arrowwith a circle on theend.
FIGURE6.5 StructurechartforProgram6.3
PascalProgram6.3issimilartotheCProgram6.3forthefollowing:•Theflagforthequadraticequationispassedasoneofthevariablesinthe
parameterofquadratic_equ(rtype).•Thequadraticequationroottypesaredefinedasconstantsusingconst.
6.4.2EquivalentParallelResistanceCProgram6.3 uses pointers to determine the equivalent parallel resistance oftwo resistors. A basic structure chart, given in Figure 6.6, shows thatget_values() returns the variablesR1 andR2; in order to change their valuesthey are sent as pointers. It also shows that the variables sent tocalc_parallel_res() are R1, R2 and R_equ is returned. Variables R1, R2 andR_equarethenpassedintoprint_results().
FIGURE6.6 Structurechartforprogram6.3
PascalProgram6.4givesthePascalequivalentofthisprogram.
Testrun6.2showsasamplerun.
6.5Exercises6.5.1.Writeaprogramwithasinglemodulethatreturnsboththevalueofmand
cforastraightline,givenpassedvaluesof(x1,y1)and(x2,y2).Theequationofthestraightlineisgivenby:
ExamplecallsforCandPascalare:
wherex1,y1,x2,y2arethecoordinates,misthereturngradientandcisthereturnedvalueforthepointatwhichthelinecutsthey-axis.
6.5.2.Writeaprogramwhichcontainsamodulewhichispassedtwoparameters.Themoduleshouldarrangethevaluesoftheparameterssothatthefirstparameteristhelargest.
6.5.3.Resistorsarenormallyidentifiedbymeansofacolourcodingsystem,whichisgiveninTable6.1.Figure6.7showsa4-bandresistor,wherethefirsttwobandsgiveadigit,thethirdamultiplierandthefourththetolerance.Writeaprogram,withparameterpassing,inwhichtheuserentersthefirstthreevaluesofthecodeandtheprogramdeterminestheresistorvalue.Thevaluerangeofinputsisbetween0and9andAsamplerunisshowninTestrun6.3.
Table6.1Resistorcolourcoding
FIGURE6.7 4-bandresistorcolourcode
6.5.4.Writeamodule,withparameterpassing,inwhichaminimumandmaximumvaluearepassedtoitandthemodulereturnsbackanenteredvaluewhichisbetweentheminimumandmaximumvalue.
ExamplecallsforCandPascalare:
whereministheminimumvalue,maxisthemaximumvalueandvalisthereturnvalued.
Usethisprogramwiththepreviousexercisesothattheenteredvaluesarebetween0and9.
Worksheet9:W9.1.Writeaprogramwhichhasamodulewhichconvertsacomplexnumber
inrectangularformintopolarform(magnitudeandangle).Themoduleshouldhavetwovaluespassedtoit(xandy)andreturntwovaluesforthemagnitudeandangleofthecomplexnumber(magandangle).Thesevaluesaredeterminedusing:
then
ExamplecallsforCandPascalare:
W9.2.Writeaprogramwhichhasamodulewhichconvertsacomplexnumberinpolarformintorectangularform(realandimaginary).Themoduleshouldhavetwovaluespassedtoit(magandangle)andreturntwovaluesfortherealandimaginarypartsofthecomplexnumber(xandy).Thesevaluesaredeterminedusing:
then
ExamplecallsforCandPascalare:
7
Arrays
7.1Introduction
Anarraystoresmorethanonevalue,ofacommondatatype,underacollectivename. Each value has a unique slot and is referenced using an indexingtechnique.Figure7.1showsacircuitwith5resistors,whichcouldbedeclaredwithaprogramwith5simplefloat(inC)orreal(inPascal)declarations.Iftheseresistorvariableswererequiredtobepassedintoafunctionall5wouldhavetobepassedthroughtheparameterlist.Aneatermethodusesarraystostoreallofthevaluesunderacommonname(inthiscaseR).Thusasinglearrayvariablecanthenbepassedintoanyfunctionthatusesit.
FIGURE7.1 Simplevariablesagainstarrayindexing
7.2CarraysThe declaration of an array specifies the data type, the array name and thenumber of elements in the array in brackets ([]). The following gives thestandardformatforanarraydeclaration.
Figure7.2showsthat thefirstelementof thearrayis indexed0andthe lastelement as size–1. The compiler allocates memory for the first elementarray_name[0]tothelastarrayelementarray_name[size–1].Thenumberofbytesallocatedinmemorywillbethenumberofelementsinthearraymultipliedbythenumberofbytesusedtostorethedatatypeofthearray.
FIGURE7.2 Arrayelements
Thefollowinggivessomeexamplearraydeclarations:
7.2.1PointersAndArraysIn C, there is a strong relationship between pointers and arrays. A pointervariablestoresamemoryaddresswhichcanbemodified,whereasanarraynamestoresafixedaddress,settothefirstelementinthearray.Theaddressofthefirstelement of an array named arrname is thus &arrname [0]. Table 7.1 showsexamplesofhowarraysandpointersusedifferentindexingnotationsandhowitispossibletointerchangethem.
Table7.1Relationshipbetweenarraysandpointers
Figure7.3showstwoarraydeclarationsforarrname.Eachhasfiveelements;the first is arrname [0] and the last arrname [4]. The number of bytesallocatedtoeachelementdependsonthedatatypedeclaration.Achararrayusesonebyteforeachelement,whereasanintarraywilltypicallytake2or4bytes.Thearraynamearrname is set to theaddressof the first elementof thearray.Eachelementwithinthearrayisreferencedwithrespecttothisaddress.
FIGURE7.3 Arrayelements
Table7.2givessomeexamplesofarrayandpointerstatements.
Table7.2Examplesofarrayandpointerstatements
Statements Description
inttmp[100]; declareanarraynamedtmpwith100elements
tmp[1]=5; assign5tothesecondelementofarraytmp*(tmp+1)=5/ equivalenttopreviousstatement
ptr=&tmp[2]; getaddressofthirdelement
7.2.2PassingArraysToCFunctionsAtcompilationthecompilerreservesenoughspaceforallelementsinanarray
andinitializesthearraynametothestartofit.Inorderforafunctiontomodifythe array the base address is passed through the parameter list. The functionitself does not know themaximum number of elements in the array; unless aparameter relating to the maximum number of elements in the array is alsopassed.Itisthuspossibletorunofftheendofanarrayandaccessmemorynotallocatedtothearray.The notation used to signify that an array is being passed in a function is
square brackets (this signifies that it is a fixed address and not a pointervariable).Thefollowinggivesanexampleofarraypassing.
7.3PascalarraysInPascal,thedeclarationofanarrayspecifiesthedatatype,thearraynameandthe number of elements in the array in brackets ([]). The following gives thestandardformatforanarraydeclaration.
Thisdeclaresanarrayoftypedatatypewiththefirstelementofarray_name[startval] to the last array element array_name [endval]. The following givessomeexamplearraydeclarationsandassignments.
7.3.1PassingArraysToFunctionsIn order to pass an array into aPascal function or a procedure the arraytypemust first be defined. This is achieved with the type keyword and an arraydefinition is normally done before any of the procedures or functions. Forexampletodefineanarraytypewith100elementsofrealvalues:
andanexamplearrayisdeclaredwith:
When an array is passed into a function or a procedure, the type definitionmustbeused todefine the array type.The following sectionof codegives anexampleof arraybeingpassing intoa function. In this case thearray typehasbeendefinedasarrtypeandthenameofthearrayinthemainprogramisarr1.Inthefunctionthearraynameisarrayin.
If an array is passed to a procedure, the only way that the procedure canmodifythecontentsofanarraysothatwhenitscontentsarechangedwhentheprocedurehascompletedistoputthevarkeywordinfrontofitsdeclarationin
the parameter list. The following shows an example of two procedureswhichcanmodifythecontentsofanarray.Inthefirst,fill_arr,thefunctionmodifiesthearraypassedtoitasthereisavarinfrontofitintheparameterlist.Iftherewasnovarinfrontofthearraynamethenthecontentsofthepassedarraycouldbemodifiedwithin this functionbutwhen the functionwas complete then thearraywhich ispassed to thefill_arr function (array1)wouldnothavebeenmodified.Inthecopy_arrprocedure,thefirstarraypassed(arr1)doesnothaveitscontentschangedasthereisnovarkeywordinfrontofitintheparameterlist,whereasthesecondarraypassed(arr2)hasthevarkeywordinfrontofit.Thesectionofthecodeshouldfillanarraywithenteredvalues(arr1)andthencopythisarrayintoanother(arr2).
7.4Examples7.4.1RunningAverageProgramProgram7.1IsA3-PointRunningAverageProgram.This
TypeOfProgramHasALow-PassFilterResponseAndCanFilterDataSamples.Figure7.4IllustratesHowTheOutputIsAFunctionOfTheAverageOfThreeElementsInTheInputArray;ThisIsAchievedByGeneratingARunningAverage.
FIGURE7.4 Arrayelements
Thefirstandlastvaluesoftheprocessedarraywilltakeonthesamevaluesastheinputarrayastherearenotthreevaluesoverwhichtotakeanaverage.Testrun7.1showsasamplerunwith10enteredvalues.
7.4.2SortingProgramProgram7.2isanexampleofasortingprogramwhereanarrayispassedtothesort function, which then orders the values from smallest to largest. Thealgorithminitiallychecksthefirstvalueinanarraywithalltheothervalues.Ifthevalueinthefirstpositionisgreaterthanthesampledarrayvaluethenthetwovaluesareswapped.Figure 7.5 shows an example of how a 6-element array can be sorted to
determine the smallestvalue. In the first iteration thevalueof20 is comparedwith22.Since20issmallerthan22thevaluesarenotswapped.Next,thevalueof20 iscomparedwith12(the thirdelement),as this issmaller thevaluesareswapped. This now makes 12 the first element. This continues until the lastvalue(15)istested.Attheendoftheseiterationsthesmallestvalue(3)willbethe first element in the array. As the first element now contains the smallestvalue the operation can now continue onto the second element. This is testedagainst the third, fourth, fifth and sixth elements and so on. The number ofiterationsrequiredtocompletethisprocesswillthereforebe15(5+4+3+2+1).
7.4.3PreferredValuesInC,theinitializationofanarraywithvalues(orcharacters)isdefinedbetweenasetofbraces({}).Thefollowinggivesthestandardformatfor initializinganarray:
Program7.3determinesthenearestpreferredresistorvalueintherange10to100Ω.Aninitializedarraypref_values[]containsnormalizedpreferredvaluesof10,12,15,18,22,27,33,39,47,56,68,82and100Ω.In Pascal, it is not possible to initialize an array with values. Thus the
set_prefprocedureisusedtofillupthepref_valuesarray.Thefind_nearest_pref functiondetermines thenearestpreferredvalue. Its
operationusesthedifferencebetweentheenteredvalueandanindexvalueinthepreferred value array. If the difference is less than the difference between thepreviousnearestvalueandtheenteredvaluethenthecurrentpreferredvaluewilltakeonthecurrentindexedarrayvalue.Figure7.6showsabasicstructurechartfor thisprogram(note, theset_pref functionhasbeen includedfor thePascalequivalentprogram).Testrun7.3showsasamplerun.
7.5.2.ModifyProgram7.3sothatitdeterminesthenearestpreferredresistorvaluebetween10and100ΩforthesetofpreferredvaluesgiveninTable7.3.
Table7.3Preferredresistorvalues
7.5.3.Writeafunctionwhichscalesanenteredrealvaluesothatitscalesitbetween10and100anddisplaysthenumberofzeros.AsamplerunisgiveninTestrun7.4.
Possiblealgorithmis:
where,afterthesecodesarecomplete,thevalueofvalwillbebetween10and100andthenum_zeroswillhavethenumberofscalingzeros.
7.5.4.Modifytheprogramin7.2sotheusercanenteranyvalueofresistanceandtheprogramwilldeterminethenearestpreferredresistorvalue.Testrun7.5givesasamplerun.Hint:writeafunctionwhichscalestheenteredvaluebetween10and100Ω(aswritteninExercise7.5.3)thenpassthescaledvaluetothepreferredvalue’sfunction.
7.5.5.Modifytheprogramin7.2sotheusercanenteranyvalueofresistanceandtheprogramwilldeterminethenearestpreferredresistorvalue.Testrun7.5givesasamplerun.Hint:writeafunctionwhichscalestheenteredvaluebetween10and100Ω(aswritteninExercise7.5.3)thenpassthescaledvaluetothepreferredvalue’sfunction.
7.5.6.Figure7.7showsanalternativerepresentationoftheprogramdevelopedinSection7.4.1withthearrayvaluesrepresentedastimesampledvalues,wheretheDrepresentsasingletimestepdelay.Inthiscasetheinputvaluevalueisdelayedbyasingletimestep(Input[i–1])andtwotimesteps(Input[i–2]).Therepresentationoftheoutputcanbewrittenas:
FIGURE7.7 Averagingsystemfortimesampling
Fortheinputdataof:
Determinetheoutputforthefollowingfunctions:(i)
(ii)
(iii)
Assumethattheprevioussamplestoi=0arezero.Testrun7.6givesasamplerunof (i) andProgram7.4 shows a sampleprogramwhichdoesnot have anyfunctionsorprocedures.
valueenteredbytheuser.W10.2.RepeatW10.1withaminimumfunction.W10.3.Writeaprogramwhichwillfillanarraywithvaluesforthefunction:
for;x=1to10(thatis,1,2,3,4,5,…10).W10.4.ModifytheprograminW10.3forarangeof–1to1,withastepof0.1
in-between(thatis,–1,–0.9,–0.8,…0.8,0.9,1).
8
Strings
8.1Introduction
Strings are one-dimensional arrays containing characters. In most cases thenumberofcharactersastringhaswillvary,dependingon the input.Thus theymustbedeclaredwiththemaximumnumberofcharactersthatislikelytooccur.InPascal, stringsare relativelyeasy touse;whereas strings inCare relativelycomplex, but C has the advantage of having powerful string manipulationroutines.
8.2PascalstringsPascalhasaspecialdatatypereservedforcharacterarrays,whichisstring.Thestringsizecanbesetasthestandardformofanarraydeclaration.Forexample:
Ifthestringsizeparameterisexcluded,suchas:
thenthestringisassumedtohaveasizeof255characters.Table 8.1 lists the routines (functions and procedures) which are used to
manipulatestringsandTable8.2shows theroutineswhichareused toconvertfromnumericvalueintostrings,andvice-versa.
Table8.1Pascalarrayroutines
Table8.2Pascalstringconversionroutines
Program8.1showsanexampleprogramwhichusesstrings.Theassignmentoperator(:=)isusedtoassignonestringtoanother(inthiscase,str1tostr2).Thelength function isalsoused todetermine thenumberofcharacters in theenteredstring.Amajorproblem in softwaredevelopment is toguardagainst incorrectuser
input. Typically a user may enter a string of characters instead of a numericvalue, or a real value instead of an integer. Program 8.2 contains a function(get_int) which overcomes this problem. In this function the user enters aninputintoastring(inp).Thisstringisthenconvertedintoanumericvalueusingthevalfunction.Oneoftheparametersofthevalfunctioniscode.If,afteritis
called,it isazerothenthestringhasbeensuccessfullyconverted,elseeitherastringorarealvaluewasentered.Theuserwillbetoldthattheinputisinvalidandwillbe repromptedforanothervalue (as therepeat…untilcondition isfalse).Theequivalentfunctiontogetarealvalueis:
8.3CcharacterarraysInCanarrayissetupwithanarrayofcharacters,suchas:
The end of a string in C is identified with the ASCII Null or terminationcharacter(‘\0’).Ifdoublequotesareusedtodefineastring,suchas“Cap1”,thenaNullcharacterisautomaticallyappendedontoit.Ifthestringisloaded,asanarray,with single characters then theNull charactermust be inserted after thelast character.For example, if the string tobe loaded is“Cap1” then the arrayelements would be ‘C, ‘a’, ‘p’, ‘1’, ‘\0’. In Figure 8.1 the string “Res–1” is
terminatedinaNullcharacter(thatis,00000000b).
FIGURE8.1 Exampleofstringallocation
Strings are character arrays with maximum size. The string name is thememoryaddressforthefirstcharacterinthestring.Foradeclaredstringofcharname[SIZE],thearraynamenameisafixedaddressatthestartofthestringandSIZE the number of characters reserved inmemory for the string. Figure 8.1shows a sample string allocation in memory; the declared string contains amaximumof11characters.Themaximumnumberofdisplayablecharacters inthestoredstringwillonlybe10astheNullcharacterterminatesthestring.Aswitharrays,thefirstcharacterofastringdeclaredascharstr1[SIZE]is
indexed as str1 [0] and the last as str1 [SIZE–1]. As with arrays, it ispossibletooverruntheendofastring(especiallyiftheterminationcharacterisnotpresent).Thiscancausedatatobereadfromorwrittentoareasofmemorynotassignedforthispurpose.Thedimensionedstringshouldalwayscontainatleastthemaximumnumberofenteredcharacters+1.Ifastringisreadfromthekeyboardthenthemaximumnumberofcharactersthatcanbeenteredislimitedby the keyboard buffer. A macro BUFSIZ, defined in stdio.h, can be used todetermineitssize.
8.3.1StandardStringFunctionsThere are several string handling functions in the standard library; most areprototyped in string.h. Table 8.3 lists these. All the string functions return avalue;forexample,Strlen()returnsanintegervaluerelatingtothelengthofastringandthefunctionsstrcat(),strupr(),strlwr()andstrcpy()returnpointers to the resultant string. This pointer can be used, if required, but theresultantstringisalsopassedbackasthefirstargumentofthesefunctions.Thestrcmp()functionreturnsa0(zero)onlyifbothstringsareidentical.
Table8.3Themainstringhandlingfunctions
CProgram8.1showshowsscanf()scansastringwithdifferentdatatypes.Inthiscase,theuserentersastringoftext.Thefirstwordofthestringisread
asastring(res_name)and thesecondasa float (res_values).Thesscanf()returns the number of fields successfully scanned; if the number of fieldsscanned is equal to2 thevariableokay is set toTRUE and thedo{}while()loopwillthusend.Ifitisnotequalto2theokayvariableissettoFALSEandanerrormessageisdisplayed,theuserwillthenbepromptedtore-enterthevalues.
Testrun8.2showsasamplerun.
C Program 8.2 uses the string function strcmp(). The do{} while() loopcontinuesuntiltheuserenterstheword“exit”.Testrun8.3showsasamplerun.
8.4Examples8.4.1CountingTheNumberOfCharactersProgram8.3ContainsAFunction(Nochars())WhichScansAStringAndDeterminesTheNumberOfOccurrencesOfAGivenCharacter.ItUsesGets()ToReadTheStringAsItAcceptsSpacesBetweenWords.Thefunctionnochars()usespointerarithmetictoreadeachofthecharacters
inthepassedstringuntilaNullcharacter.Thegetchar()functionisusedtogetthesearchcharacter.Testrun8.4showsasamplerun.
8.4.2SettingUpAnArrayOfStringsInC,thesimplestwayofsettingupanarrayofstringsistodefineanewstringdatatype.InCprogram8.4anewdatatypenamedstringisdefinedusingthestatementtypedefcharstring[BUFSIZ].An arrayof strings is then set upusing thedeclarationstringdatabase[MAX_COMP_NAMES].Each string in thearraycancontainamaximumofBUFSIZcharacters(notethiscanbechangedtoanysizeifrequired)andcanbeaccessedusingnormalarrayindexing.
TheequivalentPascalprogramisgiveninPascalProgram8.4.Inthiscaseanewdatatypeofdeclared(str_arr)whichisanarrayofstrings.
8.4.3ImpedanceOfAParallelRCCircuitTheprogramin thissectiondetermines the impedanceofaparallelRCcircuit.Figure8.2givesaschematicofthiscircuit.Theimpedanceofthiscircuitcanbefoundusingtheproductoftheimpedancesoverthesum.Thus:
FIGURE8.2 ParallelRCcircuit
Themagnitudeoftheimpedanceisthus:
Astructurechart foraprogramwhichdetermines thismagnitudeisgiveninFigure8.3(notethatforclaritytheparameterspassedtothetwoofthecallstothe get_float() function have not been included). The get_parameters()function gets three variables (Res, Cap and freq); parallel_impedance()determinestheinputimpedanceandreturnsitbackintothevariableZin.Finally,print_impedance()displaystheinputparametersandcalculatedimpedance.
FIGURE8.3 StructurechartforProgram8.7
The get_float() (or get_real() in Pascal) function gets a value by firstputtingtheenteredinformationintoastringandthenconvertingitintoafloatingpointvalue.Iftheconversionfailsthentheuserisaskedtore-enterthevalue.Italsocontainsacheckfortheminimumandmaximumvalueoftheenteredvalue.
Testrun8.7showsthattheusercanenteravalueintheincorrectformatandthe program will reprompt for another. Notice that the user has entered thestrings“none”and“fred”;theprogramcopeswiththeseandrepromptsforaninput.
8.5Exercises8.5.1.Explainwhyitisbettertoinputnumericvaluesasastringandthen
convertingittoanumericvalueratherthanenteringitwithscanf()(inC)orreadln()(inPascal).
8.5.2.Writeaprogramthatdeclaresthefollowingsevenstrings.
Storethesestringsasasinglearrayofstringsnamedmenubydeclaringanarrayofstrings.Theprogramshoulddisplaythesestringsasmenuoptionsusingaforloop.Testrun8.8showsasamplerun.
8.5.3.ModifytheprograminExercise8.5.2sothattheusercanenterthemenuoption.Theprogramwilldisplayamessageontheoptionselected.Testrun8.9showsasamplerun.
8.5.4.Modifysomeprogramsinpreviouschapterssothatprogramparametersareenteredusingtheget_float()(orget_real())function.
8.5.5.Writeafunctionthatwillcapitalizeallthecharactersinastring.8.5.6.RepeatExercise8.5.5butmakethecharacterslowercase.8.5.7.Writeafunctionthatwilldeterminethenumberofwordsinastring.Worksheet11:W11.1.Writeaprograminwhichtheuserentersastringoftextandthenpresses
theRETURNkey.Theprogramwillthendisplaythenumberofcharactersintheenteredtext.AsamplerunisshowninTestrun8.10.
W11.2.Writeaprograminwhichtheuserentersastringofeither“sin”,“cos”or“tan”andthenavalue.Theprogramwillthendeterminethecorrespondingsine,cosineortanofthevalue.AsamplerunisshowninTestrun8.11.
W11.3.ModifytheprograminW11.2sothattheprogramreadsintheenteredvalueasastringandconvertsittoarealvalue.Theprogramshouldrepromptifthevalueisinvalid.
W11.4.Writeaprograminwhichtheuserentersanumberofnames,eachfollowedbytheRETURNkey.Theendofthenamesissignifiedbyenteringnocharacters.Theprogramshouldstoretheseinanarrayofstringsandthendisplaythemtotheuser.AsamplerunisshowninTestrun8.12.
9
FileI/O
9.1Introduction
Informationoncomputersisorganizedintodirectoriesandfiles.Typicallyfileshavea filename followedbya filenameextensionwhich identifies the typeoffile. This file extension is important in some operating systems, such asWindows95andWindowsNT,asitidentifiestheapplicationprogramwhichisassociatedwiththefile.Table9.1showssometypicalfiletypes.
Table9.1Typicalfiletypes
FileseithercontaintextintheformofASCII(atextfile)orabinaryfile.AtextfileusesASCIIcharactersandabinaryfileusesthebinarydigitswhichthecomputeruses tostorevalues. It isnotnormallypossible toviewabinary filewithoutaspecialprogram,butatextfilecanbeviewedwithatexteditor.Figure9.1showsanexampleof twofileswhichcontainfour integervalues.
Thebinaryfilestoresintegersusingtwobytesin2scomplementsignednotation,whereasthetextfileusesASCIIcharacterstorepresentthevalues.Forexample,
the value of –1 is represented as1111111111111111 in 2s complement. Thisbinarypatternisstoredtothebinaryfile.ThetextfileusesASCIIcharacterstorepresent–1(thesewillbe‘-’and‘1’),andthebitpatternstoredforthetextfilewillthusbe00101101(ASCII‘-’)and00110001(ASCII‘1’).Ifanewlineisrequired after eachnumber then anew-line character is inserted after it.Note,thereisnonew-linecharacterinASCIIanditistypicaltorepresentanew-linewithtwocharacters,acarriagereturn(CR)andalinefeed(LF).InC,thenew-linecharacterisdenotedby‘\n’.
FIGURE9.1 Filepointer
Thefilepointermovesaseachelementisread/written.Figure9.2showsafilepointerpointingtothecurrentpositionwithinthefile.
FIGURE9.2 Binaryandtextfiles
Thenumber of bytes used to store eachof the elementswill dependon thedatatypeofthevariable.Forexample,alongintegerwillbestoredasfourbytes,whereas a floatingpoint value canbe stored as four bytes (on some systems).The floating point format differs from an integer format; the standard floatingpointformatusesasign-bit,asignificandandanexponent.TheendofthefileissignifiedbyanEOFcharacter.
9.2PascalfileI/OPascalhasaverybasicsetoffileinput/output.ThefunctionsusedaredefinedinTable9.2.
Table9.2PascalfileI/Ofunctions
Function Description
assign(fptr,fname) Assignsafilepoint(fbtr)toafile(fname).
rewrite(fptr) Createsandopensafilewhichhasbeenassignedwithfbtr.
reset(fptr) Opensanexistingfilewhichhasbeenassignedwithfbtr.
write(fptr,val) Writesavalue(val)toafilewhichhasbeenassignedwithfbtr.
read(fptr,val) Readsafilewhichhasbeenassignedwithfbtrandputsthevalueintoval.
InPascal,afilepointerisdefinedeitherwiththetextkeyword(foratextfile)orwith:
Thusafilepointerforanintegerfilewouldusethefollowing:
PascalProgram9.1readsinanumberofintegervaluesandwriteseachoneinturntoafile(‘out.dat’).Theprograminitiallyassignsthefilenametothefilepointer (fout) using the assign function. Next the file is created with therewritefunction.Eachvaluethatisenteredisthenwrittentothefileusingthewritefunction.Theprogramkeepspromptingforvaluesuntiltheuserentersa–
1value.Whenthishappenstheprogramwillexittherepeat…untilloop.Thefilepointeristhenresettothestartofthefilewiththeresetfunction.Nextthevaluesarereadbackusingthereadfunction.Finally,afterthe–1valueisread-in,thefileisclosedwiththecloseroutine.
9.3CfileI/OThere are 11 main functions used in file input/output (I/O), which are listedbelow. The fprint() and fscanf() functions are similar to printf() andscanf(),buttheiroutputgoestoafile.
Afilepointerstores thecurrentpositionofa readorwritewithina file.Alloperationswithinthefilearemadewithreferencetothepointer.Thedatatypeofthispointerisdefinedinstdio.handisnamedFILE.
9.3.1OpeningAFile(Fopen())Afilepointerisassignedusingfopen().Thefirstargumentisthefilenameandthe second a stringwhich defines the attributes of the file; these are listed inTable9.3.
Table9.3Fileattributes
Attribute Function
“r” openforreadingonly
“w” createforwriting
“a” append;openforwritingattheend-of-fileorcreateforwritingifthefiledoesnotexist
“r” openanexistingfileforupdate(readandwrite)
“w+” createanewfileforupdate
“a+” openforappend:open(orcreateifthefiledoesnotexist)forup-dateattheendofthefile)
Thedefaultmodeforopeningfilesis text,butatattributecanbeappendedonto the attribute string to specify a text file. For example, the attribute “wt”
opensatextfileforwriting.Abinaryfileisspecifiedbyappendingabontotheattributestring.Forexample,“rb”willopenabinaryfileforreading.Theformatofthefopen()functionis:
Iffopen()iscompletedsuccessfullyafilepointerwillbereturned,andthisisinitializedtothestartofthefile.IfwasnotabletoopenthefilethenaNULLwillbereturned.Therecanbemanyreasonswhyafilecannotbeopened,suchas:•Thefiledoesnotexist.•Thefileisprotectedfromreadingfromand/orwritingto.•Thefileisadirectory.Itisimportantthataprogramdoesnotreadfromafilethatcannotbeopened
as it may cause the program to act unpredictably. A test for this condition isgivennext.
9.3.2ClosingAFile(Fclose())Onceafilehasbeenuseditmustbeclosedbeforetheprogramisterminated.Afile which is not closed properly can cause problems in the file system. Thestandard format is given next; the return value (rtn) returns a 0 (a zero) onsuccess,otherwiseEOFifanyerrorsoccur.ThemacroEOFisdefinedinstdio.h.
The feof() function detects the end-of-file character. It returns a non-zerovalue (that is, a TRUE) if the file pointer is at the end of a file, else a 0 isreturned.Thefunctionshownnextusesthefeof()functiontodetecttheendof
the file and also tests the return from the fscanf() so that an unsuccessfulreadingfromthefileisdisregarded.
9.3.3ReadingFromFilesTable9.4liststhemainfunctionsandexamplesusedinreadingfromfiles.
Table9.4Readingfromfiles
9.4Examples9.4.1AveragesProgramCProgram9.1 andPascalProgram9.2use text files todetermine the averagevalueofanumberoffloatingpointvaluescontainedinafile.Theget_values()functionisusedtoreadthevaluesfromafile,inthiscase,IN.DAT.Thisfilecanbecreatedusingatexteditor.
9.4.2BinaryRead/WriteCProgram9.2andPascalProgram9.3isanexampleofhowanarrayoffloatingpointvaluesiswrittentoabinaryfile.IntheCprogramthefloatingpointvaluesare writen using fwrite() and then read back using fread(). Note that theNOFILE flags returned from dump_data() and read_data() are ignored bymain().InthePascalprogramthevaluesarewrittentothefileusingwriteandreadusingthereadroutine.
9.5ReadingandwritingonecharacteratatimeInCasinglecharacterisreadfromafilewithfgetc()andreadbackwiththefputc().CProgram9.3showsanexampleofreadingacharacter,oneatatime,
fromafileandwritingittoanotherfile.PascalProgram9.4givestheequivalentprogram.Itusesthereadandwriteroutines.
9.6Exercises9.6.1.Writeaprograminwhichtheuserentersanycharacterandtheprogram
willdeterminethenumberofoccurrencesofthatcharacterinthespecifiedfile.Forexample:
9.6.2.Writeaprogramwhichwilldeterminethenumberofwordsinafile.(Hint:countthenumberofspacesinthefile.)9.6.3.Writeaprogramwhichwilldeterminethenumberoflinesinafile.Apossiblemethodistocountthenew-linecharacters.
9.6.4.Writeaprogramwhichwillgetridofblanklinesinaninputfileandwritestheprocessedfiletoanoutputfile.Exampleinputandoutputfilesaregivennext.
Worksheet12:W12.1.Writeaprogramwhichwilldeterminetheaverage,thelargestandthe
smallestvaluesofatextfilecontainingfloatingpointvaluesinatextform.
W12.2.Writeaprogramwhichwillcountthenumberofcharactersinafile.Hint:readthefileonecharacteratatime.
W12.3.Writeaprogramwhichwillcounttheoccurrencesoftheletter‘a’inafile.Hint:readthefileonecharacteratatime.
W12.4.ModifyProgram9.1sothattheoutputiswrittentoafile.
10
StructuresandRecords
10.1Introduction
Astructure(or, inPascal,arecord)isanidentifiableobjectthatcontainsitemswhichdefineit.Theseitemsarelinkedunderacommongrouping.Forexample,anelectricalcircuithascertainpropertiesthatdefineit.Thesecouldbe:•Acircuittitle.•Circuitcomponentswithidentifiablenames.•Circuitcomponentswithknownvalues.Forexample,acircuitmayhavea titleof“RCFilterCircuit”, thecircuit
componentsarenamed“R1”,“R2”and“C1”andthevaluesoftheseare4320Ω,1200Ωand1μF,respectively.Thetitleandthecomponentnamesarecharacterstrings,whereasthecomponentvaluesarefloatingpoints.Astructure(orrecord)groups theseproperties into a single entity.Thesegroupings are referred to asfieldsandeachfieldismadeupofmembers.
10.2RecordsinPascalA structure is a type that is a composite of elements that are distinctive andperhapsofdifferentdatatypes.Thefollowingisanexampleofastructurewhichwill store a single electrical component. The record variable declared, in thiscase,isComponent.Ithasthreefieldsofdifferingdatatypes;cost(afloat),code(aninteger)andname(acharacterstring).
The dot notation (.) accesses each of the members within the record. Forexample:
Pascal Program 10.1 is a simple database program. The database stores arecord of a single electrical component which includes its name(Component.name), its cost (Component.cost) and its code number(Component.code).Thenameisastring,thecodeasignedintegerandthecostafloatingpointvalue.
Testrun10.1showsasamplerun.
Pascal Program 10.2 contains a procedure to print the record(print_component ()). To pass a structure into a function the data type ofparameterpassedmustbedefined.Forthepurposethetypekeywordisusedtodefineanewdatatype,inthiscase,itisnamedcomp.
Testrun10.2showsasamplerun.
Pascal Program 10.3 uses a function to get data into the record(get_component()).Theparameterpassedintothisfunctionhasavarinfrontoftheparametersothatitcanbepassedbacktothecallingroutine.
Testrun10.3showsthattheresultsareidenticaltothepreviousrun.
10.3StructuresinCA structure is a type that is a composite of elements that are distinctive andperhapsofdifferentdata types.The followinggives an exampleof a structuredeclaration(inthiscasethestringshavebeendeclaredwithamaximumof100characters).
Thefollowingisanexampleofastructurewhichwillstoreasingleelectrical
component. The structure variable declared, in this case, is Component. It hasthreefieldsofdifferingdatatypes;cost(afloat),code(aninteger)andname(acharacterstring).
The dot notation (.) accesses each of thememberswithin the structure. Forexample:
CProgram10.1isasimpledatabaseprogram.Thedatabasestoresarecordofa single electrical component which includes its name (Component.name), itscost (Component.cost) and its codenumber (Component.code).Thename is astring,thecodeasignedintegerandthecostafloatingpointvalue.
Testrun10.4showsasamplerun.
Note that the structure could have been set up at initialization using thefollowing:
CProgram10.2containsa function toprint the structure (print_component()).Topassastructureintoafunctionthedatatypeofparameterpassedmustbedefined.Forthepurposethetypedefkeywordisusedtodefineanewdatatype;inthiscase,itisnamedCompType.Theprogramalsousesbracestoinitializethefieldswithinthestructure.
Testrun10.5showsasamplerun.
CProgram10.3usesafunctiontogetdataintothestructure(get_component()).Theparameterpassedintothisfunctionwillbeapointertothebaseaddressofthestructure.Forthispurpose,anampersandis insertedbeforethestructurename. The structure pointer operator (->) is usedwith the structure pointer toaccessamemberofafield.
Testrun10.6showsthattheresultsareidenticaltothepreviousrun.
10.4ArrayofstructuresAnarrayofstructurescanbesetupinawaysimilartonormalarrayindexing.Whenanarray isdeclared thecompilerassignsenoughmemory toholdall itselements. Program 10.4 is similar to Program 10.3, but uses an array ofstructurestostoreupto5electricalcomponents.Figure10.1showsastructurechartof thisprogram. Itusesget_float() andget_int() to filterany invalidinputsforthecostandcodeofacomponent.ThesefunctionsweredevelopedinChapter 9 and have been reused as they have beenwell tested and are easilyported intoanyprogram.Thecostof theelectrical components isnow limitedbetween0and1,000andthecomponentcodefrom0to32,767.Aget_string()functionhasalsobeenadded toget thenameof thecomponent.Test run10.7showsasamplerun.
FIGURE10.1 StructurechartforProgram10.4
10.4.1ComplexArithmeticProgram 10.5 uses a structure (or record) tomultiply to complex numbers. Ifthesecomplexnumbersarea+jbandc+jdandtheresultiszthen:
Thisoperationisimplementedinthefunction(procedure)multi_complex().Testrun10.8givesatestrunfortheresultof3+j4and6+j2.
10.5Exercises10.5.1.Writeadatabaseprogram,basedonProgram10.4,whichgivesamenu
choiceastowhethertheuserwishestoenterinputanewelectriccomponent,tolistallthecomponentsalreadyinthedatabase,ortoexittheprogram.AsamplerunisgiveninTestrun10.9.
10.5.2.Writeaprogramwhichconvertsfromrectangularnotationtopolarform.Inrectangularnotation:
inpolarformthisis:
10.5.3.Writeaprogramusingstructures(orrecords)withcompleximpedancevaluesthatwilldeterminetheparallelimpedanceoftwoimpedancesZ1andZ2.Theformulafortheimpedancesinparallelisgivenbelow:
10.5.4.Writeaprogramwhichcontainsthefollowingcomplexnumbermanipulationroutines:(i)complexnumberadd.
(ii)complexnumbersubtract.(iii)complexnumbermultiply.(iv)complexnumberdivide.
10.5.5.Modifythedatabaseprograminthetextsothattheusercanselectanoptionwhichwillorderthecomponentnamesinalphabeticorder.
11
IntroductiontoC++
11.1Introduction
C is an excellent software development language for many general purposeapplications.Itsapproachisthatdataandassociatedfunctionsaredistinct,datais declared and the functions are then implemented. Object-orientedprogramming languages allow the encapsulation of a set of data types andassociatedfunctionsintoobjects.Theseobjectsareintegratedentities.C++isbyfarthemostpopularobject-orientedlanguage.Itwasdevelopedby
Bjane Stoustrup at AT&T Bell Laboratories. A new programming language,basedonC++,calledJava,hassincebeendevelopedbySunMicrosystems.C++iswellsupportedandtherearemanydifferentdevelopmentsystems.Figure11.1shows Microsoft Visual C++ Version 4.0. Microsoft Visual Version 5.0 issimilar but has enhanced support for WWW applications. The default fileextensionforaC++programisCPP.
FIGURE11.1 MicrosoftVisualC++
11.2EnhancementstoC++C++hasmanyenhancementsoverC.Theseinclude:I/Ostreamsupport.Thisfacilityallowsdatatobedirectedtoaninputand/or
anoutputstream.Section11.3outlinesthis.Objects. An object incorporates data definitions and the declaration and
definitionsoffunctionswhichoperateonthatdata.Classes. These are used to implement objects and can be initialized and
discardedwith constructors anddestructors, respectively.Section11.6outlinesthis.Complex numbers. C++ supports the usage of complex numbers and their
mathematicaloperations.Section11.7outlinesthese.Datahiding.Thisallowscertaindata tobehidden frompartsofaprogram
whicharenotallowedaccesstoit.Section11.6outlinesthis.Overloading.Thisallowsmore thanonedefinitionandimplementationofa
function.Section11.5outlinesthis.Virtual functions. This allows any one of a number of multiple defined
functionstobecalledatrun-time.Templateclasses.Thisallowsthesameclasstobeusedbydifferentdata.
11.3I/OstreamInC,outputissenttothestandardoutputusingtheprintf()function.InC++,standardinputandoutputaretakenfromstreams.Thestandardoutputstreamiscout(normallytothemonitor)andthestandardinputstreamistakenfromcin(normallyfromthekeyboard).Tobeabletousethesestreams,theiostream.hheader filemust be included in the program. The redirection operator (<<) isused todirect thedata to the inputoroutput.Program11.1showsanexampleprogramandTestrun11.1showsasamplerun.
Program11.2showsanotherexampleandTestrun11.2showasamplerun.
11.4CommentsC++supportssinglelinecommentwithadoubleslash(//)ormultilinecommentwhich are defined between a (* and a *). The single line comment makeseverythingonthelineafterthedoubleslashacomment.Afewexamplesare:
11.5FunctionoverloadingOften theprogrammerrequires tocalla function inanumberofwaysbutstillwants the same name for the different implementations. C++ allows thiswithfunction overloading.With this the programmerwrites a number of functionswith the same number but which are called with a different argument list orreturn type. The compiler then automatically decides which one should becalled. For example, in C++ Program 11.3 the programmer has defined threesquare functions named sqr(). The data type of the argument passed is of adifferent type for each of the functions, that is, either an int, a float or adouble. The return type is also different. In this program, three variables, ofdifferent types, have been declared in the main() function. The compilerwillthencallthecorrectformatfunctionforeachofthecalls.Testrun11.3showsasamplerun.Itcanbeseenthattheimplementationofthesquarefunctionwithafloatdatatypeproducessomeroundingerrors.
Theargumentlistoftheoverloadedfunctiondoesnothavetohavethesamenumberof arguments for eachof theoverloaded functions.C++Program11.4shows an example of an overloaded functionwhich has a different number ofarguments for each of the function calls. In this case, the show_results()function can either be calledwith amessage, followedby three values, or thethreevalues,orwithasinglevalue.
11.6ClassesClassesareageneralformofstructures(struct).InC,astructgatherstogetherdatamembersandinC++thestructmayalsohavefunctionmembers.Themaindifferencebetweenaclassandastructisthatinastructallmembersofthe
structure are public, while in a class the members are, by default private(restricted).Inaclass,membersaremadepublicwiththepublickeyword,andprivatewiththeprivatekeyword.C++Program11.3showsanexampleofaclass.Itcanbeseenthatitissimilar
toastructure,butthatsomepartsoftheclassareprivatewhileothersarepublic.Thesearedefinedasfollows:•Apublicmemberofaclasscanbeaccessedbyexternalcodethatisnotpart
oftheclass.Oftenthepublicmemberisafunction.•Aprivateclassmembercanonlybeusedbycodedefinedinamember
functionofthesameclass.It is obvious that all classesmust have a public content so that they canbe
accessed by external functions. In C++ Program 11.5 the circuit class has aprivatepart, in thiscase, thevariablertemp.Thepublicpartsare thefunctionsparallel()andserial(),whichdeterminetheparallelandseriesresistanceoftwo resistors. In the main function the class is declared to c1. The seriescalculationiscalledwithc1.series(r1,r2)andtheparallelcalculationiscalledwithc1.parallel(r1,r2).
Theclasswouldgetcumbersomeifthefunctionswithinitwheretobedefinedinit.C++Program11.6showshowthefunctionscanbedefinedinanotherpartoftheprogram.Inthiscasetheclassnameisdefinedfollowedbyadoublecolon(::)andthenthefunctionname.
Theprivatepartofaclassistypicallyusedtostorevariableswhicharelocal
onlytotheclass.AnexampleisshowninC++Program11.7wherethevariableslocaltothecircuitclassarer1andr2.Theget_res()functionisthenusedtosetthesevaluesandtheothertwofunctionsthenusethem.
Inmanycasestheuseofpassingparametersbypointerscanbeeliminatedbyusingclasses.ThisisshowninC++Program11.8wheretheget_res()functionis private to the circuit class. Then within the series() and parallel()functionstheget_res()functioniscalled.Notethatnootherfunctioncancallthisfunctionasitisprivatetocircuit.
11.7ComplexnumbersC++containsa rangeof functionswhich supportcomplexnumbers.Theseareprototypedincomplex.handareoutlinedinTable11.1.
Table11.1Complexfunctionsprototypedincomplex.h
Thedatatypecomplexisusedtodeclareacomplexvariable.InC++Program11.9 the variable z has been declared a complex variable. The complex()function is used to convert thex andy variables into a complex number.Thefunctionsreal(),imag(),conj(),abs()andpow()areusedandTestrun11.6displaysasamplerun.
11.8Exercises11.8.1.Writeanoverloadedfunctionwhichdeterminesthegradientofastraight
line.Theparameterspassedareeithertwo(x,y)coordinates(x1,y1x2,y2)orifthechangeinxandthechangeiny(dx,dy).Thegradientwillbecalculatedasfollows:
11.8.2.Writeanoverloadedfunctionwhichdeterminestheangleofastraightline.Theparameterspassedareeithertwocoordinates(x1,y1,x2,y2)orifthechangeinxandthechangeiny(dx,dy).Thegradientwillbe
calculatedasfollows:
11.8.3.ThefollowingC++classdefinitioncontainsdatefunctions.Theget_date()functionshouldfillthevariablesday,monthandyear.Thevalid_data()functionshouldthentestiftheentereddateisvalid.
WriteaC++programwhichcontainsthisclassdefinition.11.8.4.C++Program11.10hasamathfunctionclasswhichcontainsmultiply
anddividefunctions.Writeaprogramwhichaddsseveralothermathematicalfunctions,togivethefollowing:
11.8.5.ModifyExercise11.8.4sothatthevaluesareenteredfromthekeyboard.11.8.6.ThefollowingC++classdefinitioncontainsaninitialization,increment,
decrementanddisplayingfunctions.Theinitializationfunctionshouldinitializethesamplesvariableto0;theincrementfunctionshouldaddoneontothesamplesvariable;thedecrementshouldtakeoneawayfromsamplesandtheshow_samplesdisplaythesamplesvalue.CompletetheclassdeclarationandwriteaC++whichcallsit.Theincrementfunctionshouldbecalledwhenthe‘j’keyispressed(followedbytheRETURNkey)andthedecrementfunctionshouldbecalledwhenthe‘1’key(followedbytheRETURNkey)ispressed.ThevalueofsamplesshouldbedisplayedwhentheRETURNkeyispressedwithouteitherthe‘j’or‘1’keys.
11.8.7.Usingthecomplexnumberfunctionsdeterminethefollowing,forthecomplexnumbera=4+i5andb=6+i10:(a)a+b(b)axb(c)a-b(d)a÷b(e)a2(f)b3(g)|a|(h)ea(i)√a
Notethatinelectricalengineeringacomplexnumberistypicallyrepresentedasa+jb.
12
MoreC++
12.1Constructorsanddestructors
Aconstructorallowsfortheinitializationofaclassandadestructorallowstheclassfunctiontoberemovedfrommemory.Theyaredefinedasfollows:•Aconstructorisaspecialinitializationfunctionthatisautomaticallycalled
wheneveraclassisdeclared.Theconstructoralwayshasthesamenameastheclassname,andnodatatypesaredefinedfortheargumentlistorthereturntype.Normallyaconstructorisusedtoinitializeaclass.
•Adestructorisamemberofafunctionwhichisautomaticallycalledwhentheclassisdestroyed.Ithasthesamenameastheclassnamebutisprecededbyatilde(~).Normallyadestructorisusedtoclean-upwhentheclassisdestroyed.
C++Program12.1hasaclasswhichisnamedclass_ex.Theconstructorforthisclassisclass_ex()andthedestructoris~class_ex().Testrun12.1showsasamplerun.ItcanbeseenthatinitiallywhentheprogramisrunthemessageConstructing is displayed. This is because the class is initially declared toc1.Then when the function test() is called the Constructing message is againdisplayedasanewclassisdefined(c2).Whentheprogramleavesthisfunctionthe destructor is called and thus themessageDestructor is displayed. Finally,whentheprogramquitsthedestructorisagaincalled.
12.2FunctiontemplatesFunctiontemplatesallowfunctions tobecapableofoperatingonargumentsofanydatatype.Todefineafunctiontemplatethefollowingisdone:•Prefixthefunctionwiththetemplatekeyword.•Defineoneormoreidentifiersthatdefineparameterizedtypeswithinangled
brackets.InC++Program12.2 the template is created for amaximum() function.The
templatedefinition:
definesthatnumbercanbeofanydatatype.Thus:
couldbematchedtoanyoneofthefollowing:
Thedefinitionofthefunctionisgivenas:
12.3ClasstemplatesThe class template is a generalization of the function template. These allowcollectionsofobjectsofany typeusing thesameclass template.Program12.3showsanexampleofaclasscalc_current.Inthiscasethetemplateisdefinedas:
whichdefines thatnumbercanbeofanydata type.Whendefining theclassvariablethedatatypeisdefined.Forexample,todefinethedatatypeofnumberasanint,then:
orasafloat:
In the case ofC++Program12.3 the classwhich uses anintwill performintegeroperationsandthefloatdeclarationwillperformfloatoperations.
12.4I/OstreamsThe standard C++ library provides an expanded set of functions, templates,string-handling classes and many other enhancements to C. One of the mainenhancementsisthestreamI/Olibrary.ThestreamI/OlibrarygetsridsofaparticularprobleminCwherefunctions
such as printf() and scanf(), gives run-time errors when the data they arehandlingisintheincorrectdataform.Forexample:
wouldcreateanerror if iwasdeclaredasafloating-pointvalue.ThestreamI/Ofunctionforinputfromthestandardinputis:
Thisallowsforautomaticdatatypeconversion.TosupportthestreamI/Othestdio.h header file has been replaced by the header files iostream.h,fstream.handiomanip.h,andclasseswhichareautomaticallydefinedare:
cout forstandardoutput.
cin forstandardinput.
cerr forstandarderror
The stream I/O class hierarchy is given in Figure 12.1. The ios (I/O state)classisdeclarediniostream.h,anditcontainsinformationaboutthestateofthestream. It includes functionswhich are used to open and close streams, and italsohasstreamformatflags.
FIGURE12.1 Blockdiagramofasimplecomputersystem
The file I/O classes ifstream and ofstream are declared in the header filefstream.h. and the classiostream inherits bothistream andostream, and isdeclared in iostream.h.ifstream inherits all the standard input streamoperationsdefinedbyistream and adds a fewmore, such as constructors andfunctionsforopeningfiles.ofstreamsimilarlyrelatedtoostream.Finally,fstream,declared in theheader file fstream.h, inherits iostreamand
containsfunctionsandconstructorsthatallowfilestobeopenedininput/outputmode.Theclassescanbesummarizedby:
AbstractStreamBaseClass
ios Streambaseclass.
InputStreamClasses
istream General-purposeinputstreamclassandbaseclassforotherinputstreams.
ifstream Inputfilestreamclass.
OutputStreamClasses
ostream General-purposeoutputstreamclassandbaseclassforotheroutputstreams.
ofstream Outputfilestreamclass.
Input/OutputStreamClasses
iostream General-purposeinput/outputstreamclassandbaseclassforotherinput/outputstreams.
fstream Input/outputfilestreamclass.
12.4.1OpeningAndClosingAFileThe functions used to open and close a stream are open() and close (),respectively.
open()Foraprogram tousea file stream(fstream) itmust firstbeassociatedwithaspecificdiskfilewiththeopenfunction.Thisfunctionisusedwithanassociatedopen_mode flag, which can be combined together with the bitwise OR (|)operator.Table12.1definestheseflags.
Table12.1Fileopenflags
Flag Function
ios::app Opensanoutputfileforappending.
ios::ate Opensanexistingfileandsetsthefilepointertotheendofthefile.
ios::binary Opensfileinbinarymode(Notethatthedefaultmodeistextmode).
ios::in Opensaninputfile.Useios::inasanopen_modeforanofstreamfiletopreventtruncatinganexistingfile.
ios::nocreate Openthefileonlyifitalreadyexists.Otherwisetheoperationfails.
ios::noreplace Opensthefileonlyifitdoesnotexist.Otherwisetheoperationfails.
ios::out Opensanoutputfile.Whenyouuseios::outforanofstreamobjectwithoutios::app,ios::ate,orios::in,ios::truncisimplied.
ios::trunc Opensafileanddeletestheoldfile(ifitalreadyexists).
Todeclareafilepointertheclassofstreamisused.Forexample,todeclareastreamofmyfilewhichhasthefilenameofout.datandisanoutputfile:
This typeofdeclarationcanbeusedwhen the streamhasa fixednameandfile_openflag.It isalsopossibletousetheopenfunctiontoopenthefile.Thefollowingachievesthesameastheprevioussampleprogram.
Thefollowinggivesanexampleofabinaryfilewhichisonlyforinput:
whilethefollowinggivesanexampleofabinaryfilewhichisonlyforinputandoutput:
close()Theclosemember function isused toclose the fileassociatedwithanoutputfilestream.Thefstreamdestructorautomaticallyclosesthefilewhentheclassis destroyed. It is typically usedwhen the stream needs to be associatedwithanotherfile.C++Program12.4opensafileforoutputandwritesthecharacter‘H’toitand
thenclosesthefile.
12.4.2TextI/OThetwomainfunctionsusedfortextI/Oareput()andget().
put()Theputmember functionwrites a single character to the output stream.C++Program12.4showsanexampleoftheput()function.
get()The unformatted get member function works like the >> operator with twoexceptions:•Thegetfunctionincludeswhite-spacecharacters,whereastheextractor
excludeswhitespace.•Thegetfunctionislesslikelytocauseatiedoutputstream(cout,for
example)tobeflushed.Toextractastring:
Ortoextractasinglecharacter:
where nCount is the maximum number of characters to store the line anddelimisthedelimitercharacter(whichbydefaultisanew-line).
getline()Thegetlinemember function is similar to theget function,but theydifferasthegetfunctionleavestheterminatingcharacterinthestream;whereasgetlineremovestheterminatingcharacter.C++Program12.5givesanexampleofthegetline()function.
12.4.3ErrorProcessingFunctionsTheI/Ostreamlibrariesalsocontainanumberofmemberfunctionswhichcanbeusedtotestforerrorswhilereadingandwritingtoastream.Table12.2liststheseflags.
Table12.2Errorprocessingfunctions
Function Returnvalue
bad ReturnsTRUEifthereisanunrecoverableerror.
fail ReturnsTRUEifthereisanunrecoverableerrororan“expected”condition,suchasaconversionerror,orifthefileisnotfound.
error,orifthefileisnotfound.
good ReturnsTRUEifthereisnoerrorcondition(unrecoverableorother-wise)andtheend-of-fileflagisnotset.
eof ReturnsTRUEontheend-of-filecondition.
clear Setstheinternalerrorstate.Ifcalledwiththedefaultarguments,itclearsallerrorbits.
rdstate Returnsthecurrenterrorstate.
C++ Program 12.6 shows an example programwhich uses the fail() andgood()functions.Thefail()functionallowstheprogramtotestifthefilehasbeenopenedandthegood()functionallowstheprogramtotestiftheend-of-filehasbeenreached(orifanerrorhasoccurred).
Notethat:
canbereplacedby:
as the ! operator is overloaded to perform the same function as the fail()function.
12.4.4FilePointersTheseekg()andtellg()areusestoset(seekg)orget(tellg)thecurrentfilepoint for an input stream.On the output stream theseekp() andtellp() areused.Theseekgformatis:
where pos specifies the new position value, off is the new offset value,(streamoff and streamposare a typedef equivalent to a long int) anddir is theseekdirectionwhichmustbeoneofthefollowing:
C++ Program 12.7 gives an example of a file pointer being set to thebeginningofafilewithmyfile.seekp(01,ios::beg)),where01representsazerooffsetandios::begtheflagforthebeginningofthefile.Thetellg()formatis:
wherethestreampostypeisalongint.
12.4.5BinaryI/OreadThe read member function is similar to the read function in C. It reads aspecified number of bytes from a file into specified areas of memory. C++Program12.7givesanexampleasinglefloatingpointvaluebeginningwrittentoafileandthenreadback.
writeThewritememberfunctionissimilartothewrite()functioninC.Itwritesaspecifiednumberofbytesfrommemoryintoafile.C++Program12.8givesanexampleofwritinga10elementarraytoafileandthenreadingitback.
12.5Exercises12.5.1.ModifyC++Program12.2sothatitimplementsaminimumfunction.12.5.2.Usingafunctiontemplatewriteaprogramwhichwillcalculatethe
currentinacircuitwherethevoltageandresistancecaneitherbeints,floatsordoubles.Thecurrentisgivenby:
12.5.3.Writeaprogramwhichwillreadthetextfromafilein.datandcopyit,onecharacteratatime,tothefileout.dat.
12.5.4.Writeaprograminwhichtheuserenters10floating-pointvaluesfromthekeyboard.Theprogramshouldthenstorethesetoabinaryfile(file1.dat).Finallythefileshouldberead-backtocheckitscontents.
13
Introduction
13.1Introduction
High-level languages such as C, Pascal, Basic and FORTRAN are useful inrepresentingoperationsinanalgorithm-likemanner.Thesehigh-levellanguagestendtohidemuchofthesystemoperationsawayfromtheprogrammer.Inmostcases, the operation of the program within the computer is invisible and thelocationofthedataortheprogramcodeinmemoryisalsounimportant.Thisisimportantinmostapplicationsastheprogrammercanforgetaboutmuchofthelow-leveloperationsandgetonwithhigh-leveloperationssuchasmathematicalcalculations,graphics,andsoon.TherearethreemainreasonsforlearningAssemblyLanguage,theseare:•Itincreasestheunderstandingoftheoperationofthecomputer.•AssemblyLanguagecodesgenerallycanbeusedtofinelytunetheoperation
ofthecode.Thisfinetuningoftenspeeds-uptheoperationoftheprogram.Thisisbecausehigh-levelcompilersdonotalwaysoptimizethegeneratedcodeforspeed.
•Togainaccesstocertainhardwareoperations.Many programs use a mixture of a high-level language and Assembly
Languageformachineortimecriticaloperations.
13.2BasiccomputerarchitectureThemainelementsofabasiccomputersystemareacentralprocessingunit(ormicroprocessor),memory,andinput/output(I/O)interfacingcircuitry.Theseareconnectedbymeansof threemainbuses: theaddressbus; thecontrolbus;andthedatabus,asillustratedinFigure13.1.Externaldevicessuchasakeyboard,display,diskdrives,andsoon,canconnectdirectlyonto thedata,addressandcontrol bus or can be connected via the I/O interfacing circuit. A bus is acollectionofcommonelectricalconnectionsgroupedbyasinglename.
FIGURE13.1 Blockdiagramofasimplecomputersystem
MemorynormallyconsistsofRAM(randomaccessmemory)andROM(readonlymemory).ROMstores permanent binary information,whereasRAM is anon-permanentmemoryandwillloseitscontentswhenthepoweristakenaway.Applicationsof this typeofmemory includerunningapplicationprogramsandstoringtemporaryinformation.Themaincontrollerforthecomputeristhemicroprocessor.Itfetchesbinary
instructions from memory, decodes these instructions into a series of simpleactionsandcarriesouttheactionsinasequenceofstepswhicharesynchronizedbyasystemclock.Toaccessalocationinmemorythemicroprocessormustputtheaddressof the locationon theaddressbus.Thecontentsat thisaddressarethenplacedon thedatabus and themicroprocessor reads thedataon thedatabus.Tostoredatainmemorythemicroprocessorplacesthedataonthedatabus.Theaddressofthelocationinmemoryisputontheaddressbusandthedataisthenreadfromthedatabusintotherequiredmemoryaddresslocation.Theclassificationofamicroprocessorrelatestothemaximumnumberofbits
itcanprocessatatime,thatistheirwordlength.Theevolutionhasgonefrom4-bit,8-bit,16-bit,32-bitandto64-bitarchitectures.
13.3BitsandbytesAcomputeroperatesonbinarydigitsnamedbits.Thesecaneitherstorea‘1’ora‘0’(ON/OFF).Agroupof4bitsisanibbleandagroupof8bitsabyte.These8-bits provide 256 different combinations of ON/OFF, from 00000000 to11111111.A16-bitfieldisknownasawordanda32-bitfieldasalongword.Binarydataisstoredinmemorieswhichareeitherpermanentornon-permanent.Thisdataisarrangedasbytesandeachbytehasadifferentmemoryaddress,as
illustratedinFigure13.2.
FIGURE13.2 Memorystorage(eachaddressholdseightbits).
13.3.1BinaryNumbersAcomputeroperatesonbinarydigitswhichuseabase-2numberingsystem.Todeterminethedecimalequivalentofabinarynumbereachcolumnisrepresentedby 2 raised to the power of 0, 1, 2, and so on. For example, the decimalequivalentsof10000001and01010011are:
Thus01001111gives:
Thenumberofdecimalvalues that abinarynumbercan represent relates tothenumberofbits.Forexample:•8bitsgives0to28–1(255)differentrepresentations;•16bitsgives0to216–1
(65535)differentrepresentations;•32bitsgives0to232–1(4294967295)differentrepresentations.
Themost significant bit (msb) is at the left-hand side of the binary numberandtheleastsignificantbit(lsb)ontheright-handside.Toconvertfromdecimal(base-10)tobinarythedecimalvalueisdividedby2recursivelyandremaindernoted.Thefirstremaindergivestheleastsignificantdigit(LSD)andthelastthe
mostsignificantdigit(MSD).Forexample:
Thus110110inbinaryis54decimal.
13.4BinaryarithmeticThebasicbinaryadditionoperationisgivennext.
Thisisusedwhenaddingtwobinarynumberstogether.Forexample:
13.5NumbersandrepresentationsNumbersarestoredinseveraldifferentways.Thesecanbe:•integersorfloatingpointvalues.•singleprecisionordoubleprecisionnumbers.•signedorunsignedintegers.
13.5.1NegativeNumbersSigned integers use a notation called 2s complement to represent negativevalues.Inthisrepresentationthebinarydigitshavea‘1’inthemostsignificant
bitcolumnifthenumberisnegative,elseitisa‘0’.Toconvertadecimalvalueinto 2s complement notation, the magnitude of the negative number isrepresentedinbinaryform.Next,allthebitsareinvertedanda‘1’isadded.Forexample,todeterminethe16-bit2scomplementofthevalue–65,thefollowingstepsaretaken:
Thus,–65is111111111011111in16-bit2scomplementnotation.Table13.1shows that with 16 bits the range of values that can be represented in 2scomplementisfrom–32767to32768(thatis,65536values).
Table13.116-bit2scomplementnotation
Whensubtractingonevaluefromanother thevaluetobe takenawayisfirstconvertedinto2scomplementformat.Thisisthenaddedtotheothervalueandtheresult is in2scomplement.Forexample, tosubtract42from65,first42isconvertedinto2scomplement(that is,–42)andaddedtothebinaryequivalentof65.Theresultgivesacarryintothesignbitandacarry-out.
Fora16-bitsignedintegercanvaryfrom–32768(1000000000000000)to
32767 (0111111111111111).AsimpleCprogram toconvert froma16-bitsignedintegerto2scomplementbinaryisgiveninProgram13.1.
AsamplerunisgiveninTestrun13.1.
13.5.2HexadecimalAndOctalNumbersInassembly languagebinarynumbersare representedwithaproceedingb, forexample010101111010band101111101010barebinarynumbers.Binarydigitsare often commonly represented in hexadecimal (base 16) or octal (base 8)representation.Table13.2showsthebasicconversionbetweendecimal,binary,octal and hexadecimal numbers. In assembly language hexadecimal numbershave a proceeding h and octal number an O. For example, 4 3 F1h is ahexadecimalvaluewhereas4310oisoctal.
Table13.2Decimal,binary,octalandhexadecimalconversions
Torepresentabinarydigitasahexadecimalvalue thebinarydigitsaresplitintogroupsof fourbits (starting from the least significantbit).Ahexadecimalequivalent value then replaces each of the binary groups. For example, torepresent0111010111000000bthebitsaresplitintosectionsof4togive:
Thus, 75C0h represents the binary number 0111010111000000b. To convertfromdecimaltohexadecimalthedecimalvalueisdividedby16recursivelyandeachremaindernoted.Thefirstremaindergivestheleastsignificantdigitandthefinalremainderthemostsignificantdigit.Forexample,thefollowingshowsthehexadecimalequivalentofthedecimalnumber1103:
Thusthedecimalvalue1103isequivalentto044Fh.InC,hexadecimalvaluesareprecededbya0(zero)andthecharacter‘x’(0x)
andanoctalnumberaprecedingzero0(zero).InPascal,adollarsignisusedtosignifyahexadecimalvalue, forexample$C4.Table13.3gives someexample
formats.
Table13.3Decimal,binary,octalandhexadecimalconversions
13.6MemoryaddressingsizeThesizeoftheaddressbusindicatesthemaximumaddressablenumberofbytes.Table13.4showsthesizeofaddressablememoryforagivenaddressbussize.Forexample:
Table13.4Addressablememory(inbytes)relatedtoaddressbussize
Addressbussize Addressablememory(bytes)
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1K*
11 2K
12 4K
13 8K
14 16K
15 32K
16 64K
17 128K
17 128K
18 256K
19 512K
20 1M†
21 2M
22 4M
23 8M
24 16M
25 32M
26 64M
32 4G‡
64 16GG
*1Krepresents1024†1Mrepresents1048576(1024K)‡1Grepresents1073741824(1024M)•A1-bitaddressbuscanaddressuptotwolocations(thatis0and1).•A2-bitaddressbuscanaddress22or4locations(thatis00,01,10and11).•A20-bitaddressbuscanaddressupto220addresses(1MB).•A24-bitaddressbuscanaddressupto16MB.•A32-bitaddressbuscanaddressupto4GB.
13.7Exercises13.7.1.Completethetablebelow(assume8-bitunsignedbinaryvalues):
Decimal Binary(8-bit)
12
235
128
255
10110110
01101001
13.7.2.Determinethebinaryordecimalequivalentsforthefollowingvalues(assume16-bitvaluesand2scomplementnotation):
13.7.3.Completethetablebelow(assume16-bitsignedintegersand2scomplement):
13.7.4.Determinethefollowingsubtractionsusing2scomplementnotation(assume8-bitvaluesandtheanswershouldbein2scomplement):(i)43–21
(ii)12–46(iii)127–126(iv)0–72(v)32+75
14
ComputerArchitecture
14.1HistoryofthePC
In1959,IBMbuiltthefirstcommercialtransistorizedcomputernamedtheIBM7090/7094series.Itwassosuccessfulthatitdominatedthecomputermarketformanyyears.Later, in1965, theyproduced the famous IBMsystem360whichwasbuiltwithintegratedcircuits.Thenin1970IBMintroducedthe370system,which includedsemiconductormemories.Unfortunately, thesecomputerswereextremelyexpensivetopurchaseandmaintain.Around the same time the electronics industrywas producing cheap pocket
calculators. The development of affordable computers happened when theJapanesecompany,Busicon,commissionedasmall,atthetime,companynamedInteltoproduceasetofeighttotwelveICsforacalculator.InsteadofdesigningacompletesetofICs,IntelproducedasetofICswhichcouldbeprogrammedtoperform different tasks. Thesewere the first evermicroprocessors. Soon Intel(short for Integrated Electronics) produced a general-purpose 4-bitmicroprocessor,namedthe4004,andamorepowerful8-bitversion,namedthe8080.Other companies, such asMotorola,MOSTechnologies andZilogweresoonalsomakingmicroprocessors.IBM’s virtualmonopoly on computer systems soon started to slip asmany
companies developed computers based around the newly available 8-bitmicroprocessors, namely MOS Technologies 6502 and Zilog’s Z–80. IBM’smain contenders were Apple and Commodore who introduced a new type ofcomputer– thepersonalcomputer(PC).TheleadingsystemsweretheAppleIand theCommodore PET.These spawnedmany others, including the SinclairZX80/ZX81, the Sinclair Spectrum, the Commodore Vic-20 and the classicAppleII(allofwhichwherebasedonoraroundthe6502orZ–80).IBMrealizedthepotentialofthemicroprocessorandusedIntel’s16-bit8086
microprocessor in their version of thePC. Itwas named the IBMPC and hassincebecometheparentofall thePCseverproduced.IBM’smainaimwas to
make a computer which could run business applications, such as wordprocessors, spreadsheets and databases. To increase the production of thissoftwaretheymadeinformationonthehardwarefreelyavailable.Thisresultedinmanysoftwarepackagesbeingdevelopedandhelpedclonemanufacturerstocopytheoriginaldesign.Sotheterm‘IBM-compatible’wasbornanditquicklybecameanindustrystandardbysheermarketdominance.
14.2IntelmicroprocessorsIntel marketed the first microprocessor, named the 4004, and it caused arevolutionintheelectronicsindustrybecausepreviouselectronicsystemshadafixed functionality.With thisprocessor the functionalitycouldbeprogrammedbysoftware.Itcouldhandlejustfourbitsofdataatatime(anibble),contained2,000 transistors, operated with 46 instructions and allowed 4KB of programcodeand1KBofdata.ThesecondgenerationofIntelmicroprocessorsbeganin1974withthe8-bit
processors; these were named the 8008, 8080 and the 8085. As they couldhandlemorebitsatatimetheyweremuchmorepowerfulthantheprevious4-bitdevices.Theyweretypicallyusedinearlymicrocomputersandapplicationssuchas electronic instruments and printers. The 8008 had a 14-bit address bus andcouldthusaddressupto16KBofmemoryandthe8080hada16-bitaddressbusthusgivingita64KBlimit.The thirdgenerationofmicroprocessorsbeganwith the launchof the16-bit
processors. Intel released the 8086 microprocessor, which was mainly anextensiontotheoriginal8080processor,andthusretainedadegreeofsoftwarecompatibility.IBM’sdesignersrealizedthepowerofthe8086anduseditintheoriginalIBMPCandIBMXT(eXtendedTechnology).Ithada16-bitdatabusanda20-bit addressbus,givingamaximumaddressable capacityof1MB. Itcouldalsohandleeither8or16bitsofdataatatime(althoughinamessyway).ThePChasevolvedsinceusingIntelprocessors.A stripped-down 8-bit external data bus version called the 8088 was also
available. This stripped down processor allowed designers to produce lesscomplex(andcheaper)computersystems.Animprovedarchitectureversionofthe8088/88,calledthe80286,waslaunchedin1982,andwasusedintheIBMAT(AdvancedTechnology).In 1985, Intel introduced its first 32-bitmicroprocessor, the 80386DX.This
devicewas compatiblewith theprevious8088/8086/80286 (80×86)processors
andgaveexcellentperformance. Itcouldhandle8,16or32bitsata timeandhad a full 32-bit data and address buses. This gave it a physical addressingcapabilityof4GB.Astripped-down16-bitexternaldatabusand24-bitaddressbus version called the 80386SX was released in 1988. Thus, because of itslimitedaddressbussize,itcouldonlyaccessupto16MBofphysicalmemory.In 1989, Intel introduced the 80486DX which was basically an improved
80386DXwithamemorycacheandmathco-processorintegratedontothechip.It had an improved internal structure making it around 50% faster than acomparable 80386. The 80486SX was also introduced, which was merely a80486DXwiththelinktothemathco-processorbroken.Amajorlimitingfactoron the speed of the processor became the speed of the system clock. For thisreasonclockdoublersandtreblerswherereleasedallowedtheprocessortouseahigher clock speed than the system clock. Thus internal operationswithin theprocessorsweremuchfasterbut theprocessorhadtoslowdownto thesystemclock to communicate with external devices. Typically, systems with clockdoublerprocessorsoperatedaround75%fasterthanthecomparablenon-doubledprocessors(becausemuchoftheoperationwithinthecomputerisdonewiththeprocessor). Typical clock doubler processors areDX2–66 andDX2–50whichrunfrom33MHzand25MHzclocks,respectively.IntelalsoproducedarangeofmicroprocessorsthatrunatthreeorfourtimesthesystemclockspeedandarereferredtoasDX4processors.TheseincludetheIntelDX4–100(25MHzclock)andIntelDX4–75(25MHzclock).ThePentium(orP–5)isa64-bit‘superscalar’processor.Itcanexecutemore
thanoneinstructionatatimeandhasafull64-bit(8-byte)databusanda32-bitaddressbus,andcanoperateatspeedsfrom75MHztoover200MHz(whichrunsfromthe66MHzsystemclock).Intermsofperformance,itoperatesalmosttwice as fast as the equivalent 80486. It also has improved floating-pointoperations (roughly three times faster) and is fully compatible with previous80x86processors.Figure14.1showshowIntelprocessors interfacetoexternalequipment.
FIGURE14.1 Intelmicroprocessorsandtheirexternalinterfacing
14.380386/80486microprocessorFigure 14.2 shows themain 80386/80486processor connections.ThePentiumprocessor connections are similar but it has a 64-bit data bus. There are threemain interface connections: the memory/IO interface, interrupt interface andDMA(directmemoryaccess)interface.
FIGURE14.2 Someofthe80386/80486signalconnections.
Thewrite/read (w / ) linedetermineswhether data iswritten to (w)or readfrom ( )memory. PCs can interface directlywithmemory or can interface toisolatedmemory.Signal lineM / differentiatesbetween the two types. If it ishigh then the direct memory is addressed, else if it is low then the isolated
memoryisaccessed.The80386DXand80486haveanexternal32-bitdatabus(D0-D31)anda32-
bitaddressbusrangingfromA2toA31.Thetwoloweraddresslines,A0andA1,aredecodedtoproducethebyteenablesignals , , and .The lineactivates when A1A0 is 00, activates when A1A0 is 01, activates whenA1A0and activateswhenA1A0is11.Figure14.3illustratesthisaddressing.
FIGURE14.3 Memoryaddressing
Thebyteenablelinesarealsousedtoaccesseither8,16,24or32bitsofdataatatime.Whenaddressingasinglebyte,onlythe linewillbeactive(D0-D7);if16bitsofdataaretobeaccessedthen and willbeactive(D0-D15);if32bitsaretobeaccessedthen , , and areactive(D0-D31).The D/ linedifferentiatesbetweendata and control signals.When it is high
then data is read from or written to memory, else if it is low then a controloperationisindicated,suchasashutdowncommand.Theinterruptlinesareinterruptrequest(INTR),non-maskableinterruptrequest
(NMI)andsystemreset(RESET),allofwhichareactivehighsignals.TheINTRlineisactivatedwhenanexternaldevice,suchasaharddiskoraserialport,wishestocommunicatewith the processor. This interrupt ismaskable and the processorcan ignore the interrupt if itwants.The NMI is a non-maskable interrupt and isalwaysacted-on.When itbecomesactive theprocessorcalls thenon-maskableinterruptserviceroutine.TheRESETsignalcausesahardwareresetandisnormallymadeactivewhentheprocessorispowered-up.
14.4RegistersAll the PC-based Intelmicroprocessors are compatiblewith the original 8086processandarenormallybackwardlycompatible.Thus,forexample,aPentiumcan run 8086 and 80386 code.Microprocessors use registers to perform theiroperations.These registers are basically specialmemory locations in that theyare given names. The 8086 has 14 registers which are grouped into fourcategories,asillustratedinFigure14.4.
FIGURE14.4 8086/88registers
14.4.1GeneralPurposeRegistersTherearefourgeneralpurposeregisterswhichareAX,BX,CXandDX.Eachcanbeusedtomanipulateawhole16-bitwordorwithtwoseparate8-bitbytes.Thesebytesarecalledthelowerandupperorderbytes.Eachof theseregisterscanbeusedas two8-bitregisters;forexample,ALrepresentsan8-bitregisterwhichisthelowerhalfofAXandAHrepresentstheupperhalfofAX.The AX register is the most general purpose of the four registers and is
usuallyused for all typesofoperations.Eachof theother registershasoneormoreimpliedextrafunctions.Theseare:•AX,whichisnamedtheaccumulator.Itisusedforallinput/outputoperations
andsomearithmeticoperations.Forexample,multiply,divideandtranslateinstructionsassumetheuseofAX.
•BX,whichisnamedthebaseregister.Itcanbeusedasanaddressregister.•CX,whichisthecountregister.Itisusedbyinstructionswhichrequireto
count.Typicallyitisusedforcontrollingthenumberoftimesaloopisrepeatedandinbitshiftoperations.
•DX,whichisthedataregister.Itisusedforsomeinput/outputandalsowhenmultiplyinganddividing.
14.4.2AddressingRegistersThe addressing registers are used in memory addressing operations, such asholding the source address of thememory and the destination address. TheseaddressregistersarenamedBP,SP,SIandDI,whichare:•SI,whichisthesourceindex.Thisisusedwithextendedaddressing
commands.•DI,whichisthedestinationindex.Thedestinationisusedinsomeaddressing
modes.•BP,whichisthebasepointer.•SS,whichisthestackpointer.
14.4.3StatusRegistersStatusregistersareusedtotestforvariousconditionsinanoperation,suchas‘istheresultnegative’,‘istheresultzero’,andsoon.Thetwostatusregistershave16bitsandarecalledtheinstructionpointer(IP)andtheflagregister(F):•IP,whichistheinstructionpointer.TheIPregistercontainstheaddressofthe
nextinstructionoftheprogram.•Flagregister.Theflagregisterholdsacollectionof16differentconditions.
Table14.1outlinesthemostusedflags.
Table14.1Processorflags
14.4.4SegmentsRegistersTherearefourareasofmemorycalledsegments,eachofwhichhave16bitsandcanthusaddressupto64KB(from0000htoFFFFh).Thesesegmentsare:•Codesegment(csregister).Thisdefinesthememorylocationwherethe
programcode(orinstructions)isstored.•Datasegment(dsregister).Thisdefineswheredatafromtheprogramwillbe
stored(dsstandsfordatasegmentregister).•Stacksegment(ssregister).Thisdefineswherethestackisstored.•Extrasegment(es).Alladdressesarewithreferencetothesegmentregisters.The 8086 has a segmentedmemory, these registers are used to manipulate
thesesegments.Eachsegmentprovides64KBofmemory,thisareaofmemoryisknownasthecurrentsegment.Segmentedmemorywillbediscussedinmoredetailinthenextsection.
14.4.5MemoryAddressingThereareseveralmethodsofaccessingmemorylocations,theseare:•Impliedaddressingwhichusesaninstructioninwhichitisknownwhich
registersareused.•Immediate(orliteral)addressingusesasimpleconstantnumbertodefinethe
addresslocation.•Registeraddressingwhichusestheaddressregistersfortheaddressing(such
asAX,BX,andsoon).•Memoryaddressingwhichisusedtoreadorwritetoaspecifiedmemory
location.
14.5MemorysegmentationThe 80386, 80486 and Pentium processors run in one of two modes, eithervirtual or real.When using the virtualmode they act as a pseudo-8086 16-bitprocessor,knownastheprotectedmode.Inthereal-modetheycanusethefullcapabilities of their address and data bus. The mode and their addressingcapabilities depend on the software and thus allDOS-based programs use thevirtualmode.The 8086 has a 20-bit address bus so that when the PC is running 8086-
compatible code it can only address up to 1 MB of memory. It also has asegmentedmemoryarchitectureandcanonlydirectlyaddress64KBofdataatatime. A chunk of memory is known as a segment and hence the phrase‘segmentedmemoryarchitecture’.Memoryaddressesarenormallydefinedbytheirhexadecimaladdress.A4-bit
address bus can address 16 locations from 0000b to 1111b. This can berepresented in hexadecimal as 0h to Fh. An 8-bit bus can address up to 256locationsfrom00htoFFh.Two importantaddressingcapabilities for thePCrelate toa16-anda20-bit
addressbus.A16-bitaddressbusaddressesupto64KBofmemoryfrom0000hto FFFFh and a 20-bit address bus addresses a total of 1MB from 00000h toFFFFFh.The80386/80486/Pentiumprocessorshavea32-bitaddressbusandcanaddressfrom00000000htoFFFFFFFFh.Amemorylocationisidentifiedwithasegmentandanoffsetaddressandthe
standard notation is segment:offset. A segment address is a 4-digithexadecimal addresswhich points to the start of a 64 kB chunk of data. The
offset isalsoa4-digithexadecimaladdresswhichdefines theaddressoffsetfromthesegmentbasepointer.ThisisillustratedinFigure14.5.
FIGURE14.5 Memoryaddressing
The segment:offset address is defined as the logical address, the actualphysicaladdress iscalculatedbyshifting thesegmentaddress4bits to the leftandaddingtheoffset.Theexamplegivennextshowsthattheactualaddressof2F84:0532is2FD72h.
14.5.1AccessingMemoryUsingCAndPascalInCtheaddress1234:9876hisspecifiedas0×12349876.TurboPascalaccessesamemorylocationusingthepredefinedarraymem[](toaccessabyte),memw[](aword)ormemw[](alonginteger).Thegeneralformatismem[segment:offset].
14.5.2NearAndFarPointersAnearpointerisa16-bitpointerwhichcanonlybeusedtoaddressupto64KBofdatawhereasafarpointerisa20-bitpointerwhichcanaddressupto1MBofdata.A farpointer canbedeclaredusing the fardata typemodifier, as shown
next.
In the program shown in Figure 14.6 a near pointer ptr1 and a far pointerptr2havebeendeclared. In thebottompartof the screen theactualaddressesstoredinthesepointersaredisplayed.Inthiscaseptr1isDS:1234handptr2is0000:12 34h. Notice that the address notation of ptr1 is limited to a 4-digithexadecimaladdress,whereasptr2hasasegment:offsetaddress.Theaddressofptr1isintheformDS:XXXXwhereDS(thedatasegment)isafixedaddressinmemoryandXXXXistheoffset.
FIGURE14.6 Nearandfarpointers
Thereareseveralmodes inwhich thecompileroperates. In thesmallmodelthe compiler declares all memory addresses as near pointers and in the largemodel they are declared as far pointers. Figure 14.7 shows how the largememorymodelisselectedinBorlandC(Options→Compiler→Model→Large).The large model allows a program to store up to 1 MB of data and code.Normallythesmallmodelisthedefaultandonlyallowsamaximumof64KBfordataand64KBforcode.
FIGURE14.7 Compilingaprograminthelargemodel
14.6ViewinsidetheprocessorTobeabletoviewtheprocessortheusermustuseadebuggingprogram.Figure 14.8 shows an example of Turbo Debugger which is available with
mostoftheBorlandsoftwaredevelopmentproductsandcanbeusedtoviewtheoperation of a program. It can be seen that the machine code and equivalentassembly languagemacroappears in the top lefthandwindow.Asamplecodelineis:
FIGURE14.8 ExamplescreenfromTurboDebugger
which specifies that the memory location is 01FA in the code segment(cs:01FA).Machinecodeat this location is55 (01010101)and theequivalentAssemblyLanguageinstructionispushbp.Notethatthecssegmentaddressinthiscaseis5757h,thustheactualphysicaladdresswillbewithreferencetotheaddress57570h(seeSection14.5forafullerexplanation).Thecontentsoftheflagregisterareshownontheright-handside.Inthiscase
theflagsare:
Theregistersareshowntotheleftoftheflagregister.Inthiscasethecontentsare:
Thedata(inthedatasegment)isshownatthebottomlefthandcornerofthescreen.Thefirstline:
showsthefirst8bytesinmemory(fromDS:0000toDS:0007).Thefirstbyteinmemory is00h (0000 0000) and the next is also00h.After the 8 bytes aredefinedthe8equivalentASCIIcharactersareshown.Inthiscase,theseare:
TheASCIIequivalentcharacter for5A(10011010) is ‘T’andfor75(01110101)itis‘u’.Notethat,inthiscase,thedatasegmentregisterhas58A0h.Thusthelocationofthedatawillbereferencedtotheaddress58A00h.Thebottomright-handwindowshowsthecontentsofthestack.
14.7Machinecodeandassemblylanguage
An important differentiation is betweenmachine code and assembly language.Theactualcodewhichrunson theprocessor ismachinecode.Thesearemadeuptouniquebitsequenceswhichidentifiesthecommandandothervalueswhichthesecommandsoperateon.Forexample,forthedebuggerscreenfromFigure14.8,theassemblylanguagelinetomoveavalueintotheAXregisteris:
theequivalentmachinecodeis:
where the codeB8h(10111000b) identifies the instruction tomove a 16-bitvalueintotheAXregisterandthevaluetobeloadedis0194h(0000000110010100b).Notethatthereasonthe94hvalueisstoredbeforethe01hvalueisthatonthePCtheleastsignificantbyteisstoredinthefirstmemorylocationandthemost significant byte in the highest memory location. Figure 14.9 gives anexampleofstoragewithinthecodesegment.Inthiscasethetwoinstructionsaremovandpush.InmachinecodetheseareB8hand50h,respectively.
FIGURE14.9 Examplememorystorageforcodesegment
14.8Exercises14.8.1.ForthedebugscreengiveninFigure14.10determinethefollowing:
FIGURE14.10 ExamplescreenfromTurboDebugger
(i)ContentsofAX,BX,CX,DX,SI,DI.(ii)ContentsofAH,AL,BHandBL.(iii)Thefirstassemblylanguagecommand.(iv)Thememoryaddressofthefirstlineofcode(Hint:thecs:02C2and
thevalueinthecsregisterneedtobeused).(v)Thememoryaddressofthedata(Hint:theds:0000andthevaluein
thedsregisterneedtobeused).
15
8086/88Instructions
15.1Introduction
Thischapterdiscusses8086/88assemblylanguage.Aspreviouslymentionedallofthe80X86andPentiumprocessorscanrun8086code.The80386,80486andPentiumprocessorsruninoneoftwomodes,eithervirtualorreal.Whenusingthe virtual mode they act as a pseudo-8086 16-bit processor, known as theprotectedmode.AllDOS-basedprogramsusethevirtualmode.
15.2CharactersandnumbersIntegerscanberepresentedasbinary,octal,decimal,orhexadecimalnumbers;8086 Assembly Language represents these with a preceding B, O, D or H,respectively. A decimal integer is assumed if there is no letter. Examples ofnumericconstantsare:
Character constants are enclosedwith single quoteswhen theyhave a fixednumberofcharacters(suchas‘b’,‘fired’,andsoon),oriftheyhaveavariablenumberofcharacterstheyareenclosedwithdoublequotes(suchas“a”,“fred”,andsoon).Forexample:
15.3Comments
Assembly Language programs probably need more comments than high-levellanguageassomeoftheoperationsgivelittleinformationontheirpurpose.Thecharacter used to signify a comment is the semi-colon (;) and all commentswithinaprogramareignoredbytheassembler.Forexample,thefollowinglineshavecomments:
15.4Move(MOV)Themoveinstruction(mov)moveseitherabyte(8bits)oraword(16bits)fromoneplacetoanother.Therearethreepossiblemethods:•Movingdatafromaregistertoamemorylocation.•Movingdatafromamemorylocationtoaregister.•Movingdatafromoneregistertoanother.Notethatin8086/88itisnotpossibletomovedatadirectlyfromonememory
location toanotherusingasingle instruction.Tomovedata fromonememorylocationtoanotherthenfirst thedataismovefromthememorylocationintoaregister,nextitismovedfromtheregistertothedestinationaddress.Examplesofmovingaconstantvalueintoregistersare:
An address location is identified within square bracket ([]). Then tomovedataintoaspecifiedaddresstheaddresslocationmustbeloadedintoaregister.Forexample,toloadthevalueof50h(01010000)intoaddresslocation200hthefollowinglinesareused:
Thegeneralformatofthemovinstructionis:
Wherer/mstandsforregister(suchasAH,AL,BH,BL,CH,CL,DH,DL,AX,BX,CX,DX,BP,SI,DI) ormemory location.Andr/m/d stands for aregister, memory or a constant value. The register sr stands for any of thesegment registers (CS,DS,ES,SS)andr16/m16 stand forany16-bit register(AX,BX,CX,SP,BP,SI,DI)and16-bitmemoryaddress.
15.5AddressingmemoryAnaddresslocationcanbespecifiedwitheithertheBX,BP,SIorDIregister.Examplesare:
Program 15.1 gives an Assembly Language; it loads 1234h into addressDS:0000h,5678hintoaddressDS:0002hand22hintoaddressDS:0005h.
Figure15.1showsasamplerunofProgram15.1.Itcanbeseenthatthemov[bx],1234 operation loads the value34h into address locationDS:0000h and12h into address DS:0001h. This is because the processor loads the leastsignificantbyteintotheloweraddresslocation.
FIGURE15.1 SamplerunofProgram15.1
It can be seen from Figure 15.1 that the associated machine code for theinstructionsis:
ThusBBhisthemachinecodetoloadavalueintotheBXregister,C707hloadsasvalue into the addresspointed to andC747h loads anoffsetedvalue into anaddresslocation.
15.6Additionandsubtraction(ADDandSUB)Astheyimply,theADDandSUBperformadditionandsubtractionoftwowordsorbytes.TheADDandSUBinstructionoperateontwooperandsandputtheresultinto the first operand. The source or destination can be a register or address.Examplesare:
Thestandardformatoftheaddinstructionis
whererisanyregister,mismemorylocationanddisanyconstantvalue.
15.7Compare(CMP)TheCMP instruction acts like theSUB instruction, but the result is discarded. Itthus leaves both operands intact but sets the status flags, such as the O(overflow),C(carry),Z(zero)andS(signflag).Itistypicallyusedtodetermineif two numbers are the same, or if one value is greater, or less than, anothervalue.Examplesare:
15.8Unaryoperations(INC,DECandNEG)Theunaryoperationsoperateonasingleoperand.AnINCinstructionincrementstheoperandby1, theDEC instructiondecrements theoperandby1andtheNEGinstructionmakestheoperandnegative.Examplesare:
15.9Booleanbitwiseinstructions(AND,OR,XORandNOT)TheBooleanbitwiseinstructionsoperatelogicallyonindividualbits.TheXOR
functionyieldsa1whenthebitsinagivenbitpositiondiffer;theANDfunctionyieldsa1onlywhenthegivenbitpositionsareboth1s.TheORoperationgivesa 1 when any one of the given bit positions are a 1. These operations aresummarisedinTable15.1.Forexample:
Table15.1Bitwiseoperations
Examples of Assembly Language instructions which use bitwise operationsare:
15.10Shift/rotateinstructions(SHL,SAL,SHR,SAR,ROL,ROR,RCLandRCR)Theshift/rotateinstructionsare:
SHL–shiftbitsleft SHR–shiftbitsright
SAL–shiftarithmeticleft SAR–shiftarithmeticright
RCL–rotatethroughcarryleft RCR–rotatethroughcarryright
ROL–rotatebitsleft ROR–rotatebitsright
The shift instructionsmove thebits,withorwithout the carry flag, andcan
eitherbeanarithmeticshiftor logical shift,whereas the rotate instructionsarecyclicandmayinvolvethecarryflag.TheSHLandSHRshiftbitstotheleftandright,respectively.Theyshiftthebitstotheleftorrightwherethebitshiftedoutisputintothecarryflagandthebitshiftedinisa0.Therotateoperations(ROL,ROR,RCL,RCR)arecyclic.Rotatewithcarry instructions (RCLandRCR) rotatethebitsusingthecarryflag.Thusthebitshiftedoutisputintothecarryflagandthebitshiftinistakenfromthecarryflag.Therotatebits(ROLandROR)rotatethebitswithoutthecarryflag.TheSALinstructionisidenticaltoSHL,buttheSARinstructiondiffersfromSHRinthatthemostsignificantbitisshiftedtotheright for each shift operation. This operation, and the others, are illustrated inFigure15.2.
FIGURE15.2 Rotateoperations
Thenumberofshiftsonthevalueisspecifiedeitherasaunitaryvalue(1)orthenumberofshiftisstoredinthecounterregister(CL).Thestandardformatis
wherer/m is for registerormemoryand1stands foroneshift. Ifanymore
than one shift is required the CL register is used. These operations take adestinationandacountervaluestoredinCL.Forexample,withbitpattern:Initialconditions:01101011andcarryflag1Resultafter:
ThefollowingisanexampleoftheSARinstruction:
Aftersarax,1stores005Bh(0000000001011011b)thenthesarax,c1instructionmovesthecontentsofAXby3bitpositionstotheright.ThecontentsofAXafterthisoperationwillbe0005h(0000000000000101b).ThefollowingshowsanexampleoftheSHRinstruction:
AndanexampleoftheRORinstruction:
15.11Unconditionaljump(JMP)TheJMPinstructiontransfersprogramexecutiontoanotherpartoftheprogram.Itusesalabeltoidentifythejumplocation;thisisdefinedasanamefollowedby
acolon.TheJMPinstructionisnotconditional–theprogramwillalwaysjump.Anexampleisgivennext:
15.12ConditionaljumpsWiththeJMPtheprogramalwaysgoestothelabel,buttheunconditionaljumpswillonlybranchifacertainconditionismet,suchasiftheresultsisnegative,ortheresultiszero,andsoon.Table15.2outlinestheconditionjumpinstructions.
Table15.2Conditionaljumpinstructions
Afewexampleare:
15.13Subroutinecalls(CALLandRET)Subroutinesallowasectionofcode tobecalledand for theprogram to returnback towhere itwascalled.The instructionsareCALLandRET.Anexample isgivennext:
15.14PushandpopThe PUSH and POP instructions are typically used with subroutines. A PUSHinstructionputstheoperandontoatemporarystoragecalledastack(thiswillbecovered inmoredetail later).Thestack isaLIFO(last in, firstout)where thelast element to be loaded is the first to be taken off, and so on. The POPinstructionisusedtoextractthelastvaluewhichwasputonthestack.Typically they are used to preserve the contents of various registers so that
their contents are recovered after a subroutine is called. For example, if asubroutinemodifiestheAX,BXandCXregisters,thentheregistersareputonthestackwith:
Nextthesubroutinecanusetheseregistersforitsownuse.Finally,withinthesubroutine,theoriginalregistersarerestoredwith:
TheorderofthePOPinstructionsmustbethereverseofthePUSHinstructionssothatthecontentsareproperlyrestored.Forexample:
15.15MovingarounddatainmemoryProgram 15.2 loads the memory locations from DS:0000h to DS:00FFh withvalues starting at 00h and ending atFFh.After theALandBX registers havebeen initialized to 00h then the code runs round a loop until all the memorylocationshavebeenloaded.TheBXregistercontainstheaddressthevaluewillbeloadedto.Thisincrementseachtimeroundtheloop.TheALregisterstoresthevaluetobeloadedintothecurrentlyspecifiedmemorylocation.Figure15.3showsasamplerun.
FIGURE15.3 Sampledebugscreen
15.16AssemblerdirectivesThere are various structure directives that allow the user to structure theprogram.ThesearedefinedinTable15.3.
Table15.3Assemblerdirectives
15.17DatadefinitionVariablesaredeclaredinthedatasegment.TodefineavariabletheDB(definebyte) and DW (define word) macros are used. For example, to define (andinitialize)avariabletemp,whichhasthevalue15assignedtoit, isdeclaredasfollows:
anuninitializedvariablehasavaluewhichisaquestionmark,forexample:
Thereareotherdefinitiontypesused,theseare:
•dd(definedoubleword–2times16bitswhichis4bytes).•dq(definequadword,whichis8bytes).•dt(define10bytes).Thedata definition is definedwithin the data segment. InTurboAssembler
(TASM) the data segment is defined after the .DATA directive (as shown inTASMProgram15.4).MicrosoftAssembler(MASM)definesthedatasegmentbetweenthedatasegmentanddataends,asshowninMASMProgram15.3.Program15.3declarestwovariablesnamedval1andval2.Thevalueval1is
loadedwiththevalue1234handval2isloadedwith5678h.Figure15.4showsanexamplescreenafterthethreemovinstructionshavebeenexecuted.Itcanbeseenval1hasbeenstoredatDS:0000andval2atDS:0002.
FIGURE15.4 Sampledebugscreen
15.18Equates(EQU)Todefinea tokentoacertainvalue theEQU (equates)statementcanbeused.Forexample:
Thegeneralformatis:
Theassemblersimply replaceseveryoccurrenceof the tokenwith thevaluegiven.
15.19ExercisesPart1Inthistutorialthesamplecodeshouldbeinserted,byreplacingthehighlightedcode,intoProgram15.5.
15.19.1.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivennext.
15.19.2.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.3.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.4.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.5.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.6.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.7.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.8.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.9.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.10.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.11.Enterthefollowingcodeandrunthedebuggertodeterminethevalues
givenbelow.
15.19.12.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.13.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.19.14.Enterthefollowingcodeandrunthedebuggertodeterminethevaluesgivenbelow.
15.20ExercisesPart215.20.1.WriteanAssemblyLanguageprogramwhichcontainsafunctionwhich
addsthecontentsoftheAXandBXregistersandputstheresultintotheCXregister.
15.20.2.Writeaprogramwhichloadsthevalues00h,01h,02h,…FEh,FFhintothememorylocationsstartingfromaddressDS:0008h.Abasiclayoutisshownbelow.
15.20.3.WriteaprogramwhichwillloadthevaluesFFh,FEh,FDh,…01h,00hintothememorylocationsstartingfromaddressDS:0000h.
15.20.4.WriteaprogramwhichmovesablockofmemoryfromDS:0020hto0100htoaddresseswhichstartataddress0200h.
15.20.5.Writeaprogramwhichdeterminesthelargestbyteinthememorylocations0000hto0050h.
16
8086InterfacingandTiming
16.1Introduction
Therearetwomainmethodsofcommunicatingexternalequipment,eithertheyaremapped into thephysicalmemory andgiven a real addresson the addressbus(memorymappedI/O)ortheyaremappedintoaspecialareaofinput/outputmemory (isolated I/O). Figure 16.1 shows the twomethods. Devices mappedintomemoryareaccessedbyreadingorwritingtothephysicaladdress.IsolatedI/O provides ports which are gateways between the interface device and theprocessor.Theyare isolated from the systemusingabufferingsystemandareaccessedbyfourmachinecodeinstructions.TheINinstructioninputsabyte,oraword,andtheOUTinstructionoutputsabyte,oraword.CandPascalcompilersinterpret the equivalent high-level functions and producemachine codewhichusestheseinstructions.
FIGURE16.1 Memorymappingorisolatedinterfacing
16.2InterfacingwithmemoryThe80×86processorinterfaceswithmemorythroughabuscontroller,asshowninFigure16.2.Thisdevice interprets themicroprocessor signalsandgeneratestherequiredmemorysignals.Twomainoutputlinesdifferentiatebetweenareadorawriteoperation(R/ )andbetweendirectandisolatedmemoryaccess(M/ ).TheR/ lineislowwhendataisbeingwrittentomemoryandhighwhendataisbeingread.WhenM/ ishigh,directmemoryaccessisselectedandwhenlow,theisolatedmemoryisselected.
FIGURE16.2 AccessmemorymappedandisolatedI/O
16.3MemorymappedI/OInterface devices canmap directly onto the system address and data bus. In aPC-compatiblesystemtheaddressbus is20bitswide, fromaddress00000h toFFFFFh (1MB). If the PC is being used in an enhanced mode (such as withMicrosoftWindows)itcanaccesstheareaofmemoryabovethe1MB.Ifituses16-bit software (such asMicrosoftWindows3.1) then it can address up to 16MB of physicalmemory, from 000000h to FFFFFFh. If it uses 32-bit software
(suchasMicrosoftWindows95) then the softwarecanaddressup to4GBofphysical memory, from 00000000h to FFFFFFFFh. Table 16.1 and Figure 16.3givesatypicalmemoryallocation.
Table16.1MemoryallocationforaPC
Address Device
00000h–00FFFh Interruptvectors
00400h–0047Fh ROMBIOSRAM
00600h–9FFFFh Programmemory
A0000h–AFFFFh EGA/VGAgraphics
B0000h–BFFFFh EGA/VGAgraphics
C0000h-C7FFFh EGA/VGAgraphics
FIGURE16.3 TypicalPCmemorymap
16.4IsolatedI/O
Devicesarenotnormallyconnecteddirectlyontotheaddressanddatabusofthecomputerbecausetheymayusepartofthememorythataprogramusesortheycould cause a hardware fault. On modern PCs only the graphics adaptor ismappeddirectlyintomemory,therestcommunicatethroughaspeciallyreservedareaofmemory,knownasisolatedI/Omemory.IsolatedI/Ouses16-bitaddressingfrom0000htoFFFFh,thusupto64KBof
memory can be mapped.MicrosoftWindows 95 can display the isolated I/OmemorymapbyselectingControlPanel→System→DeviceManager, thenselecting Properties. From the computer properties window the Input/output(I/O) option is selected.Figure16.4 showsan example for a computer in therangefrom0000hto0064handFigure16.5showsfrom0378hto03FFh.
FIGURE16.4 ExampleI/Omemorymapfrom0000hto0064h
FIGURE16.5 ExampleI/Omemorymapfrom0378hto03FFh
ItcanbeseenfromFigure16.5thatthekeyboardmapsintoaddress0060hand0064h, thespeakermapstoaddress0061handthesystemtimerbetween0040hand0043h.Table16.2showsthetypicalusesoftheisolatedmemoryarea.
Table16.2TypicalisolatedI/Omemorymap
Address Device
000h–01Fh DMAcontroller
020h–021h Programmableinterruptcontroller
040h–05Fh Counter/Timer
060h–07Fh DigitalI/O
080h–09Fh DMAcontroller
0A0h–0BFh NMIreset
0C0h–0DFh DMAcontroller
0E0h–0FFh Mathcoprocessor
170h–178h Hard-disk(SecondaryIDEdriveorCD-ROMdrive)
lF0h-lF8h Hard-disk(PrimaryIDEdrive)
200h–20Fh GameI/Oadapter
210h–217h Expansionunit
278h–27Fh Secondparallelport(LPT2:)
Secondserialport(COM2:)
2F8h–2FFh Secondserialport(COM2:)
300h–31Fh Prototypecard
378h–37Fh Primaryparallelport(LPT1:)
380h–38Ch SDLCinterface
3A0h–3AFh Primarybinarysynchronousport
3B0h–3BFh Graphicsadapter
3C0h–3DFh Graphicsadapter
3F0h–3F7h Floppydiskcontroller
3F8h–3FFh Primaryserialport(COM1:)
16.4.1InputtingAByteFromAnI/OPortTheassemblylanguagecommandtoinputabyteis:
whereDX is theDataRegisterwhich contains the address of the input port.The8-bitvalueloadedfromthisaddressisputintotheregisterAL.ForTurbo/BorlandCtheequivalentfunctionisinportb().Itsgeneralsyntax
isasfollows:
wherePORTADDRESSistheaddressoftheinputportandvalueisloadedwiththe8-bitvaluefromthisaddress.Thisfunction isprototypedin theheaderfiledos.h.ForTurboPascaltheequivalentisaccessedviatheport[]array.Itsgeneral
svntaxisasfollows:
wherePORTADDRESSistheaddressoftheinputportandvaluethe8-bitvalueatthisaddress.Togainaccesstothisfunctionthestatementusesdosrequirestobeplacednearthetopoftheprogram.Microsoft C++ uses the equivalent inp() function (which is prototyped in
conio.h).
16.4.2InputtingAWordFromAPortTheassemblylanguagecommandtoinputawordis:
whereDX is theDataRegisterwhich contains the address of the input port.The16-valueloadedfromthisaddressisputintotheregisterAX.ForTurbo/BorlandCtheequivalentfunctionisinport().Itsgeneralsyntaxis
asfollows:
wherePORTADDRESSistheaddressoftheinputportandvalueisloadedwiththe 16-bit value at this address. This function is prototyped in the header filedos.h.ForTurboPascaltheequivalentisaccessedviatheportw[]array.Itsgeneral
syntaxisasfollows:
wherePORTADDRESS is the address of the input port andvalue is the 16-bitvalue at this address. To gain access to this function the statement uses dosrequirestobeplacednearthetopoftheprogram.MicrosoftC++ uses the equivalentinpw() function (which is prototyped in
conio.h).
16.4.3OutputtingAByteToAnI/OPortTheassemblylanguagecommandtooutputabyteis:
whereDX is theDataRegisterwhichcontains theaddressof theoutputport.The8-bitvaluesenttothisaddressisstoredinregisterAL.ForTurbo/BorlandCtheequivalentfunctionisoutportb().Itsgeneralsyntax
isasfollows:
wherePORTADDRESS is the address of the output port andvalue is the 8-bitvalue to be sent to this address. This function is prototyped in the header filedos.h.ForTurboPascaltheequivalentisaccessedviatheport[]array.Itsgeneral
syntaxisasfollows:
wherePORTADDRESS is the address of the output port andvalue is the 8-bitvalue to be sent to that address. To gain access to this function the statementusesdosrequirestobeplacednearthetopoftheprogram.MicrosoftC++ uses the equivalentoutp() function (which is prototyped in
conio.h).
16.4.4OutputtingAWordTheassemblylanguagecommandtoinputabyteis:
whereDX is theDataRegisterwhichcontains theaddressof theoutputport.The16-bitvaluesenttothisaddressisstoredinregisterAX.ForTurbo/BorlandCtheequivalentfunctionisoutport().Itsgeneralsyntax
isasfollows:
wherePORTADDRESS is theaddressof theoutputportandvalue is the16-bitvalue to be sent to that address.This function is prototyped in the header filedos.h.ForTurboPascaltheequivalentisaccessedviatheport[]array.Itsgeneral
syntaxisasfollows:
wherePORTADDRESS is theaddressof theoutputportandvalue is the16-bitvalue to be sent to that address. To gain access to this function the statementusesdosrequirestobeplacednearthetopoftheprogram.MicrosoftC++ uses the equivalentoutp() function (which is prototyped in
conio.h).
16.5DigitalI/Ousingthe8255Each 8255 IC has 24 digital input/output lines. These are grouped into threegroupsof8bitsandarenamedPortA,Port?andPortC.Asingle8-bitregister,knownasthecontrolregister,programsthefunctionalityof theseports.PortCcanbesplitintotwohalvestogivePortC(upper)andPortC(lower).Theportsandthecontrolregistermapintotheinput/outputmemorywithanassignedbaseaddress.ThearrangementoftheportaddresseswithrespecttothebaseaddressisgiveninTable16.3.
Table16.3PPIaddresses
Portaddress Function
BASE_ADDRESS PortA
BASE_ADDRESS+1 PortB
BASE_ADDRESS+2 PortC
BASE_ADDRESS+3 Controlregister
Figure 16.6 shows the functional layout of the 8255. The control registerprogramseachof theports tobean inputor anoutput andalso theirmodeofoperation.Therearefourmainpartswhichareprogrammed:PortA,PortB,PortC(lower)andPortC(upper).
FIGURE16.6 LayoutofPPI
Figure16.7showsthedefinitionoftheControlRegisterbits.Themsb(mostsignificantbit)D7eithermakesthedeviceactiveorinactive.Ifitissettoa0itisinactive,elseitwillbeactive.Theinput/outputstatusofPortAissetbyD4.Ifitisa0thenPortAisanoutput,elseitwillbeaninput.ThestatusofPort?issetbyD1,PortC(lower)byDOandPortC(upper)byD3.
FIGURE16.7 PPIControlRegisterBitDefinitions
PortAcanoperateinoneofthreemodes–0,1and2.ThesearesetbybitsD5andD6. If theyare set to00 thenMode0 is selected,01 toMode1and10 toMode2.PortBcanbeusedintwomodes(Mode0and1)andissetbybitD2.ExamplesofbitdefinitionsandthemodeofoperationaregiveninTable16.4.
Table16.4
Table16.4Examplebitpatternsforcontrolregister
Bitpattern Modeofoperation
01101000 DeviceisinactiveasD7setto0
10011000 Mode0PortAinput,PortC(upper)input,Mode0PortBoutput,PortC(lower)output
10101000 Mode1PortAoutput,PortC(upper)input,Mode0PortBoutput,PortC(lower)output
16.5.1Mode0Mode0isthesimplestmodewithnohandshaking.InthismodethebitsonPortCcanbeprogrammedasinputsoroutputs.
16.5.2Mode1Thismode gives handshaking for the synchronization of data.Handshaking isnormally required when one device is faster than another. In a typicalhandshakingoperationtheoriginatorofthedataaskstherecipientifitisreadytoreceive data. If it is not then the recipient sends back a ‘not ready for data’signal.Whenitisreadyitsendsa‘readyfordata’signalandtheoriginatorthensendsthedata.IfPortsAandBareinputsthenthebitsonPortChavethedefinitionsgiven
inTable16.5.
Table16.5Mode1handshakinglinesforinputtingdata
Wheninputtingdata,the goinglow(active)writesdataintotheport.Afterthis data is written into the port, the IBF line automatically goes high. Thisautomaticallyremainshighuntilthedataisreadfromtheport.Ifanyoftheportsareoutputs,thenthebitdefinitionsofPortCaregivenin
Table16.6.
Table16.6
Table16.6Mode1handshakinglinesforoutputtingdata
In thismode,when data iswritten to the port the line goes low,whichindicatesthatdataisreadytobereadfromtheport.The linewillnotgohighuntilthe ispulledlow.
16.5.3Mode2Thismodeallowsbi-directionalI/O.ThesignallinesaregiveninTable16.7.
Table16.7Mode2operationforbi-directionalI/O
16.6DigitalI/OprogramsProgram16.1outputsthebinarycodefor0to255toPortBwithaone-seconddelaybetweenchanges.Theprogramexitswhentheoutputreaches255.Adelayroutinehasbeenaddedwhichuses thesystem timer.Thiswillbediscussed inmore detail in Section 17.10. Figure 16.8 shows a typical set-up to test theprogramwherePort?hasbeenconnectedtoeightlight-emittingdiodes(LEDs).
FIGURE16.8 Possiblesystemset-up
In 8086 Assembly Language a macro is defined using the equ statement.Program 16.1 uses these to define each of the port addresses. This helps todocumenttheprogramandmakesiteasiertomakeglobalchanges.Forexample,a different base address is relatively easy to set up, as a single change toBASE_ADDRESSautomaticallyupdatesallportdefinesintheprogram.Inthiscasethebase address is1F0h.This address shouldbe changed to the requiredbaseaddressoftheDIOcard.Thestatements:
output the value90h(10010000b) to the control register (CNTRLREG). Thestatements:
initiallysettheALregisterto00h.Thenexttwostatements(movdx,PORTBandoutdx,a1)output thevalueofAL toPORTB.Next thedelay routine iscalled (withcalldelay).This routinedelays foraperiodof1second.Next the
AL register is incremented (inc a1). After this the AL register value iscomparedwith100h(000100000000b).Iftheresultofthecomparestatementisnotequaltozerothentheprogramloopsbacktotheloop1:label.
Program16.2readsthebinaryinputfromPortAandsendsittoPortB.Itwill
stoponlywhenall theinputbitsonportAare1s.Itshowshowabytecanberead from a port and then outputted to another port. Port A is used, in thisexample,as the inputandPort?as theoutput.Figure16.9showshowPortAcould be connected to input switches and Port ? to the light-emitting diodes(LEDs). Loading the bit pattern 90h into the control register initializes thecorrectset-upforPortsAandB.
FIGURE16.9 Typicalsystemset-up
16.7TimingEach instruction takes a finite time to complete. The speed of operation isdetermined by the processor clock speed. To find out how long a certaininstruction will take determine the number of clock cycles to execute it andmultiply thisby the clockperiod.For example, if the clock rate is8MHz theclock period is 0.125 μs. The following gives the number of clock cycles forvarious instructions. Note that different processors take differing numbers ofclock cycles to execute a command. Notice also that the 80386 processor isaround twice as fast as the 8086 for many of the commands. This is due toimprovedarchitecture.
Table16.8Instructiontimingsfordifferentprocessors
where(b)–bytedivide,(w)–worddivide,(nj)–nojump.For example, the mov ax, 1234 statement takes 0.5 μs assuming a 8MHz
clock.Thefollowingprogramwilloutputanincrementvalueeverytwoseconds.Note the great improvement in the 80286/386 over the 8086 on dealing withmathematicsoperations.Inthe8086ittakes144clockcyclestoperformaworddividewhilethe80386onlytakes22clockcycles(nearlyseventimesfaster).
Withinthesecond(inner)loop:
willbeexecuted64777times.Thenumberofcyclestodoadecandajnzis3+16 cycles. Thus it takes 19 cycles to complete this loop. The total time tocompletethisinnerloopisthus:Numberofcycles×clockperiod=19×0.125μs=2.375μs.Totaltimetocompletethisloopis64777×2.375μs=0.1538s.Thisinnerloopisexecuted7times,thusthetotaldelaytimeis13×0.1538=
2s.Ingeneral,forageneralpurposeloopwithAandBasthevariablesinAXand
BX,then:
Firsttheinnerloop:
ThenthenumberofcyclesforinnerloopwillbeB×19:
Numberofcycles=A×((B×19)+16+3)If 19×B ismuchgreater than19 then the following approximation canbe
made:
Thus:
Forexample,inthelastexample(assuminga4MHzclock)thevalueofAis13andBis64777,thus:Typicalprocessorclocksare:
8086 4.77MHz,8MHz.
386 16MHz,25MHz,33MHz.
486 33MHz,50MHz,66MHz,100MHz.
Pentium 60MHz,90MHz,120MHz,200MHz.
16.8Exercises16.8.1.WriteaprogramtoinputabytefromPortA.16.8.2.WriteaprogramwhichwillsendtoPortBall1’s.16.8.3.WriteaprogramwhichwillreadabytefromPortA.Thisbyteisthen
senttoPortB.16.8.4.Writeaprogramthatsendsa‘walking-ones’codetoPortB.Thedelay
betweenchangesshouldbeonesecond.A‘walking-ones’codeisasfollows:
Hint:Usetheshiftleftoperator,thatis<<orsh1.16.8.5.Writeseparateprogramswhichoutputthepatternsin(a)and(b).The
sequencesareasfollows:
16.8.6.Writeseparateprogramswhichoutputthefollowingsequences:
(e)Theinverseof(d)above.16.8.7.WriteaprogramthatreadsabytefromPortAandsendsthe1s
complementrepresentationtoPortB.Notethat1scomplementisallbitsinverted.
16.8.8.ChangetheprograminExercise16.8.9sothatitgivesthe2scomplementvalueonPortB.Hint:Eithercomplementallthebitsofthevalueandadd1orsendthenegatedvalue.
16.8.9.Writeaprogramwhichwillcountfrom00htoffhwith1sdelaybetweeneachcount.TheoutputshouldgotoPortB.
16.8.10.WriteaprogramwhichwillsamplePortAevery1sthensendsittoPortB.
16.8.11.Writeaprogramwhichwillsimulatethefollowinglogicfunctions.
wherePA0isbit0ofPortA,PA1isbit1ofPortAandPB0isbit0ofPortB.16.8.12.Writeaprogramwhichwillsimulateatrafficlightsequence.Thedelay
betweenchangesshouldbeapproximately1second.
andthesequenceis:
16.8.13.Modifytheprogramin16.8.12sothatthesequenceis:
16.8.14.WriteaprogramwhichwillinputavaluefromPortA.ThisvalueissenttoPortBandthebitsarerotatedwithadelayof1second.
16.8.15.WriteaprogramwhichwillsampleportAwhenbit0ofPortCischangedfroma0toa1.ValuesarethenenteredviaPortAbyswitchingPC0froma0toa1.Thesevaluesareputintomemorystartingfromaddress100h.TheendoftheinputsessionisgivenbyPC1beingset(iePC1isequaltoa1).WhenthisissetalltheinputvaluesaresenttoPortBwitha2sinterval.
17
8086Interrupts
17.1Interrupts(INT)
The interrupt function (INT) interrupts the processor. It can be used to gainaccess to eitherDOSorBIOS functions.BIOS functions are typicallyused togain access to the hardware, whereas DOS functions are used to quit fromprograms,readacharacterfromthekeyboardandwriteacharactertothescreen.
FIGURE17.2 Bitdefinitionsforserialportinitialization
17.2Interrupt21h:DOSservicesPrograms access DOS functions using interrupt 21h. The functionality of thecall is set by the contents of theAH register.Other registers are used either topassextrainformationtothefunctionortoreturnvaluesback.Forexample,todetermine the system time the AH is loaded with the value 2AH. Next, theprocessor is interruptedwith interrupt21H. Finally,when the program returnsfromthisinterrupttheCXregisterwillcontaintheyear,DHthemonth,DLthedayandALthedayoftheweek.
Table 17.1 is only a small section of all the DOS related interrupts. Forexample,function2Fhcontainsmanyfunctionsthatcontroltheprinter.Notethatfor the Get free disk space function the total free space on a drive isAX×BX×CXandtotalspaceondisk,inbytes,isAX×CX×DX.
Table17.1DOSinterrupts
InProgram17.1,function02h(writecharactertotheoutput)isusedtodisplaythecharacter‘A’.Inthiscase,thefunctionnumber02hisloadedintoAHandthecharactertobedisplayedisloadedintoDL.
Program17.2usesthefunction01htogetacharacterfromthekeyboardandthenthefunction02htodisplayit.
Program17.3displays thedefaultbootdrive. Inmostcases thedefaultbootdrivewillbeC.
17.3Interrupt10h:BIOSvideomodeInterrupt 10h allows access to the video display. Table 17.2 outlines typicalinterruptcalls.Program17.4uses theBIOSvideo interrupt todisplayaborderaround the screenwhichchanges colour each second fromblack to lightblue.
Thesecoloursareset-upwithanenumdatatypedefinition.Inthiscase,BLACKisdefinedas0,BLUEas1,andsoon.
Table17.2BIOSvideointerrupt
Todisplay aborder theAH register is loadedwith0Bh,BHwith00h andBLwith thebordercolour.Next, the interrupt10h iscalledwith theseparameters.Figure17.1showsthebitdefinitionforthecolours.
17.4Interrupt11h:BIOSequipmentcheckInterrupt 11h returns a word which gives a basic indication of the types ofequipmentconnected. It isuseful indetermining if there isamathcoprocessorpresentandthenumberofparallelandserialportsconnected.Table17.3showstheformatofthecall.
Table17.3BIOSequipmentcheckinterrupt
Description Inputregisters Outputregisters
Getequipmentlist AX=BIOSequipmentlistword
17.5Interrupt13h:BIOSdiskaccessInterrupt13hallowsaccesstomanydiskoperations.Table17.4liststwotypicalinterruptcalls.
Table17.4BIOSdiskaccessinterrupt
17.6Interrupt14h:BIOSserialcommunicationsBIOSinterrupt14hcanbeusedtotransmitandreceivecharactersusingRS-232and also to determine the status of the serial port. Table 17.5 lists the maininterruptcalls.Program17.5initializesCOM2:with4800baud,evenparity,1stopbitand7databits.
Table17.5
Table17.5BIOSserialcommunicationsinterrupts
17.7Interrupt17h:BIOSprinterTheBIOSprinterinterruptallowsaprogrameithertogetthestatusoftheprinterortowriteacharactertoit.Table17.7outlinestheinterruptcalls.
Table17.7BIOSprinterinterrupt
17.8Interrupt16h:BIOSkeyboardInterrupt 16h allows access to the keyboard. Program 17.6 uses the BIOSkeyboard interrupt to display characters, entered from the keyboard, to thescreen.Initially,thecode:
teststoseeifakeyhasbeenpressed.Itrepeatsuntilthezeroflagisunset(thishappenswhenakeyhasbeenpressed.Thecheckforkeystrokeinterruptcallsetsthezeroflag(ZF)iftherearenocharactersinthebuffer,otherwiseitwillbea0.
Nextthecode:
gets the key that has been pressed and puts the result into theDL register.Finally,theDOSinterruptisusedtodisplaythecharactertothescreen.
Table17.6BlOSkeyboardinterrupt
17.9Interrupt19h:BIOSrebootInterrupt19hrebootsthesystemwithoutclearingmemoryorrestoringinterruptvectors. For a warm boot, equivalent to Ctrl-Alt-Del, then 1234h should bestored at 0040h:0072h. For a cold boot, equivalent to a reset, then 0000h isstoredat0040h:0072h.CareshouldbetakenwiththisinterruptasitmaycausethePCto‘hang’.
17.10Interrupt1Ah:BIOSsystemtimeTheBIOS system time interrupt allows a program to get access to the systemtimer.Table17.8outlinestheinterruptcalls.
Table17.8BIOSsystemtimeinterrupt
17.11CandPascalinterrupts
SeeSectionD.3.
17.12Exercises17.11.1.UsingBIOSvideointerrupt10hwriteprogramswhichperformthe
following:(a)fillacompletescreenwiththecharacter‘A’ofatextcolourofred
withabackgroundofblue;(b)repeat(a),butthecharacterdisplayedshouldcyclefrom‘A’to‘Z’withaone-seconddelaybetweenoutputs;(c)repeat(a),buttheforegroundcolourshouldcyclethroughallavailablecolourswithaone-seconddelaybetweenoutputs;(d)repeat(a)sothatthebackgroundcolourcyclesthroughallavailablecolourswithaone-seconddelaybetweenoutputs.
17.11.2.UsingBIOSkeyboardinterrupt16hwriteaprogram,inCorPascal,thatdisplaysthestatusoftheShift,Capslock,Cntrl,ScrollandNumkeys.
18
Introduction
18.1Introduction
MicrosoftWindowshasbecomethede-factoPCoperatingsystem.Allversionsup to, and including,Windows 3.11 used DOS as the core operating system.NewversionsofWindows, suchasWindowsNTandWindows95donotuseDOSandcanthususethefullcapabilitiesofmemoryandoftheprocessor.ThemostpopularprogramminglanguagesforWindowsprogrammingare:•MicrosoftVisualBasic.•MicrosoftVisualC++andBorlandC++.•Delphi(whichisavailablefromBorland).VisualBasichastheadvantageovertheotherlanguageinthatitisrelatively
easytouseandtoprogramwith,althoughthedevelopmentpackageswhichareusedwithC++andDelphimakeconstructingtheuserinterfacerelativelyeasy.VisualBasicVersion4isshowninFigure18.1andVersion5isshowninFigure18.2.
18.2Event-drivenprogrammingTraditional methods of programming involve writing a program which flowsfromoneparttothenextinalinearmanner.Mostprogramsaredesignedusingatop-downstructureddesign,wherethetaskissplitintoanumberofsubmodules,these are then called when they are required. This means that it is relativelydifficult to interrupt theoperationofacertainpartofaprogram todoanotheractivity,suchasupdatingthegraphicsdisplay.VisualBasicingeneralis:•Object-oriented.Wheretheprogramisdesignedaroundanumberofready-
madeobjects.•Event-driven.Wheretheexecutionofaprogramisnotpredefinedandits
executionistriggeredbyevents,suchasamouseclick,akeyboardpress,andsoon.
•Designedfromtheuserinterfaceoutwards.Theprogramistypicallydesignedbyfirstdevelopingtheuserinterfaceandthencodedtorespondtoeventswithintheinterface.
18.3VisualBasicfilesAlistingofasampledirectorywhichcontainsVisualBasicfilesis:
Thefilesare:•Projectfiles.ProjectsbindtogethertheindividualelementsofaVisualBasic
program.Initiallytheusercreatesaprojectfilefortheprogramandthisisloadedwhenevertheprogramisbeingdeveloped.Thedefaultextensionforaprojectiseither.MAKor.VBPextension.Projectsgenerallymakeiteasiertocontrolthevariouselementsofaprogram.
•Modules.Codethatisattachedtoaformisaccessiblefromanywhereonthatform,butaprogrammayhavemorethanoneform.Itwillsometimesbenecessarytohaveprogramcodethatcanbereachedfromanyform,andinthiscasethecodewouldbewrittenonamodule.Modulesdisappearfromviewwhentheprogramruns–onlyformshaveanon-screen
existence.Theremaybeseveralmodulesinoneprogram,andeachissavedasaseparatefile.Thesearemarkedbya.BASextension.
•Forms.AformformstheanchorforallpartsofaVisualBasicprogram.Initiallyitisablankwindowandtheuserpastescontrolsontoittocreatetherequireduserinterface.Codeisthenassociatedwitheventsontheform,suchasrespondingtoabuttonpressoraslidercontrol,althoughsomecontrolelementsdonothaveassociatedcode.Aprogramcanhaveoneormoreforms,eachofwhichdisplaysandhandlesdataindifferentways.Tomakeformsshareablewithotherprogramstheneachissavedseparatelywitha.FRMextension.
•Icons.Theseare,normally,smallgraphicsimagesandhavea.ICOextension.•Graphicsimages.ThesearenormallyeitherBMP(bitmapped)filesorWMF
(windowsmetafile)fileswiththe.BMPand.WMFextensions,respectively.•Others.Otherfilesalsoexist,suchasVBXwhichisVisualBasiceXtension.
18.4OthertermsVisualBasicusesanumberofother terms todescribedesignprocedure, theseare:•Controls.TheVBinterfacecontainsawindowwithcontrolobjectswhichare
pastedontoaform.Thesecontrolscanbesimpletext,menus,spreadsheetgrids,radiobuttons,andsoon.Eachcontrolhasasetofpropertiesthatdefinestheiroperation,suchastheircolour,thefontsize,whetheritcanberesized,andsoon.Somecontrols,suchascommandbuttons,menus,andsoon,normallyhavecodeattachedtothem,butsimplecontrols,suchastextandagraphicsimagecansimplyexistonaformwithnoassociatedcode.
•Procedures.AswithCandPascal,VisualBasicusesprocedures,orsubroutines,tostructurecode.Mostoftheseareassociatedwithaneventthatoccursfromacontrolandsomewillbefree-alonewithnoassociatedevent.
18.5MainscreenFigure18.3showstheVisualBasic4desktop(VisualBasic5issimilar,butthewindowsdonot float on thedisplay). It contains amenu form, controls,mainform,projectwindowsandpropertieswindow.
FIGURE18.3 VisualBasic4desktop
18.5.1MenuBarAndToolbarThemenu bar and tool bar appear in a single, floating window, as shown inFigure18.4.Themenubarcontainsoptionsforfilemanipulation(File),editing(Edit), viewing (View), running (Run), testing the program (Debug),manipulatingwindows (Window) andgettinghelp (Help).These can eitherbeselected with the mouse, using the function key F10 and then selecting theoptionwiththearrowkeysandpressingreturnorusethehot-key.ThehotkeyisAltandtheunderlinedcharacter,thusAlt-FselectstheFilemenu,Alt-EselectstheEditmenu,andsoon.
FIGURE18.4 VisualBasic4menubarandtoolbar
Thetoolbarcontainsshortcutbuttonsforcommonlyusedmenuitems.Tothe
rightofthetoolbartherearetwoindicators;thesedisplaythepositionandsizeofa selected form or control. This area of the window is also used in thecompilationphasetodisplaythestatusofthecompilation.Thetoolbarbuttonsare:Createsanewform.Createsanewstandardmodule.Opensanexistingproject.Savesthecurrentlyactiveproject.Locks/unlocksthecontrolsontheactiveform.DisplaystheMenuEditor.DisplaysthePropertieswindow.DisplaystheObjectBrowser.DisplaystheProjectwindow.Runstheapplication.Pausesprogramexecution.Stopsexecution.
Togglesabreakpoint(breakpointonoroff).DisplaysthevalueofthecurrentselectionintheCodewindow.Displaysthestructureofactivecalls.Tracesthrougheachlineofcodeandstepsintoprocedures.ExecutescodeoneprocedureorstatementatatimeintheCodewindow.
18.5.2ProjectWindowThe Projectwindow displays all the forms andmodules used in the currentlyactiveproject;anexampleisshowninFigure18.5.AnewprojectisopenedbyselectingNewProject fromtheFilemenu,whereas toopenanexistingprojecttheOpenProjectoption is selected from theFilemenu, else theopenexistingprojectoptionisselectedfromthetoolbar.
FIGURE18.5 VisualBasicProjectwindow
Only one project can be opened at a time, but that project can have anynumberofforms.IntheProjectwindowtheusercandothefollowing:•OpenaFormwindowforanexistingformbyselectingtheformnameand
clickingtheViewFormbutton.•OpentheCodewindowforanexistingformbyselectingthemodulename
andclickingtheViewCodebutton.•RemoveafilefromaprojectbyselectingthefileintheProjectwindow,and
thenfromtheFilemenuchooseRemoveFile.
18.5.3FormWindowTheFormwindow, as shown inFigure 18.6, creates applicationwindows anddialogboxes.AnewformiscreatedbyselectingtheFormfromtheInsertmenu(orusethetoolbarshortcut)andanexistingformisopenedbyselectingtheformnameand thenclicking theViewFormbutton.Anexisting form isadded toaprojectbyselectingtheAddFilecommandfromtheFilemenu.AnyassociatedcodeonaformcanbeviewedbyclickingontheViewCodebutton.
FIGURE18.6 VisualBasicFormwindow
Each formhasaControl-menubox,MinimizeandMaximizebuttons,andatitlebar,andcanbemovedandresized.Table18.1showsthekeycombinationsintheFormwindow.
Table18.1KeycombinationinFormwindow
Keycombination Operation
alpha EnteravalueinthePropertieswindowfortheselectedproperty.
CLICK–Drag Selectmultiplecontrols.
CTRL+CLICK+DRAG Addorremovecontrolsfromthecurrentselection.
CTRL–C CopytheselectedcontrolstotheClipboard.
CTRL-CLICK Addorremoveacontrolfromtheselection.
CTRL–E DisplaytheMenuEditor.
CTRL–J Bringcontroltofront(ifcontrolsareoverlapping).
CTRL–K Sendcontroltoback(ifcontrolsareoverlapping).
CTRL–V PastefromClipboardontotheform.
CTRL–X CuttheselectedcontrolstotheClipboard.
CTRL–Z Undoadeletedcontrol.
DEL Deletetheselectedcontrols.
F4 DisplaythePropertieswindow
F7 OpentheCodewindowfortheselectedobject.
SHIFT–CTRL–alpha SelectapropertyinthePropertylistofthePropertieswindow.
SHIFT-TAB Cyclebackwardthroughcontrolsintaborder.
TAB Cycleforwardthroughcontrolsintaborder.
18.5.4ToolboxThe Toolbox contains the icons for controls. These are standardVisual Basiccontrolsandanycustomcontrolsandinsertableobjects,asshowninFigure18.7.TheToolbox is displayed, if it is not already in view,withToolbox from theViewmenuanditisclosedbydouble-clickingtheControl-menubox.
FIGURE18.7 Toolboxcontrols
Figure18.6showssometypicalcontrols,theseinclude:
• Pointer.Thepointerdoesnotdrawanycontrolobjectsandisusedtoresizeormoveacontrolonceithasbeendrawnonaform.Whenacontrolisaddedtoaformthenthepointerisautomaticallyselected.
• PictureBox.Displaysgraphicalimages(BMP,WMF,ICOorDIB).
• Label.Usedtodisplaytextthatcannotbechangedbytheuser.
• TextBox.Allowstheusertoeitherenterorchangetext.
• Frame.Usedtocreateagraphicalorfunctionalgroupingforcontrols.ThesearegroupedbyfirstdrawingaFramearoundthemandthendrawingcontrolsinsidetheframe.
• CommandButton.Usedtocarryoutacommand.
• CheckBox.Usedtocreateacheckbox,wheretheusercanindicateifsomethingisonoroff(trueorfalse),or,whenthereismorethanoneoption,amultipleofchoices.
• OptionButton.Usedtodisplayanumberofoptionsbutonlyonecanbechosen(thisdiffersfromthecheckboxwhichonlyallowsoneoptiontobechosen).
• ComboBox.Usedtogiveacombinationofalistboxandtestbox,wheretheusercaneitherenteravalueinatextboxorchooseanitemfromthelist.
• ListBox.Usedtodisplayalistofitemsandtheuserisallowedtochooseoneofthem.Thislisthasascrollbuttontoallowthelisttobescrolled.
• HScrollBar(horizontalscrollbar).Usedtoscrollupanddownthroughalistoftextorgraphicalinformation.Itcanalsobeusedtoindicatethecurrentpositiononascaleorbytheusertoindicateagivenstrengthofvalue.
• VScrollBar(verticalscrollbar).Usedtoscrollacrossalistoftextorgraphicalinformation.Itcanalsobeusedtoindicatethecurrentpositiononascaleorbytheusertoindicateagivenstrengthofvalue.
• Timer.Usedtogeneratetimedeventsatgivenintervals.
• DriveListBox.Usedtodisplaycurrentlyconnecteddiskdrives.
• DirListBox(directorylistbox).Usedtodisplaydirectoriesandpaths.
• FileListBox.Usedtodisplayalistoffiles.
• Shape.Usedtodrawshapes,suchasrectangles,roundedrectangles,squares,roundedsquares,ovalsorcircles.
• Line.Usedtodrawavarietyoflinestylesonyourformatdesigntime(transparent,solid,dash,dot,dash-dotanddash-dot-dot).
• Image.Usedtodisplayagraphicalimage,suchasabitmap(BMP),icon(ICO),ormetafile(WMF).TheseimagescanonlybeusedtodisplayandimageanddonothavethesamecontrolfunctionsasPictureBox.
• Data.Usedtoprovideaccesstodataindatabases.
• OLEController.Usedtolinkandembedobjectsfromotherapplications(suchasWordDocuments,ExcellSpreadsheets,andsoon).OLEstandsforObjectLinkingandEmbedding.
• CommonDialog.Usedtocreatecustomizeddialogboxesforoperationssuchasprintingfiles,openingandsavingfiles,settingfontsandhelpfunctions.
• DBList(data-boundlistbox).UsedasanenhancedListBoxwhichcanbecustomizedtodisplayalistofitemsfromwhichtheusercanchooseone.Thelistcanbescrolledifithasmoreitemsthancanbedisplayedatonetime.
• DBCombo(data-boundcombobox).UsedasanenhancedCombowhichcanbecustomizedtodisplayalistofitemsfromwhichtheusercanchooseone.Usetodrawacombinationlistboxandtextbox.Theusercaneitherchooseanitemfromthelistorenteravalueinthetextbox.
• DBGrid(data-boundgrid).Usetodisplayaseriesofrowsandcolumnsandtomanipulatethedatainitscells.DBGridisacustomcontrolandhasincreaseddataaccesscapabilitiesthatthestandardGriddoesnothave.
18.6PropertieswindowThe Properties window displays the properties of the currently selected form,controlormenu.Theyallowpropertiessuchasthecolour,fonttypeandsizeoftext,backgroundcolourofaform,typeofgraphicimage,andsoon.First, the item to be changed is selected and then the Properties option is
chosenfromtheViewmenu,elsethefunctionkeyF4.ThePropertywindowisclosedwithadouble-clickontheControl-menubox.ThePropertieswindowcontainstwomainparts,theseare:•TheObjectbox.Thisisfoundbelowthetitlebarandidentifiesthecurrently
selectedformorcontrolontheform.InFigure18.8thecommandbuttonhasanassociatedPropertieswindow.TheObjectboxinthiscaseis:
FIGURE18.8 Propertieswindow
WhereCommandButtonisthecontrolitemandisnamedCommand1,othercontrolitemsarePictureBox,Label,TextBox,Frame,CheckBox,OptionButton,ComboBox,ListBox,HScrollBar,VScrollBar,Timer,DriveListBox,FileListBox,Shape,Line,Image,Data,andsoon.ClickthearrowattherightsideoftheObjectbox( )togetalistofthecontrolsonthecurrentform.Fromthelist,choosethecurrentformoracontrolontheformwhosepropertiesyouwanttochange.AnexampleisgiveninFigure18.9.Inthiscasetherearethreecommandbuttons(namedCommand1,Command2andCommand3)ontheform,adrivelistbox(namedDrive1),andsoon.Thelistalsocontainsthecurrentlyactiveform(inthiscaseitisnamedForm1).Namesofcontrolsareassignedconsecutively,sothatthefirstcommandbuttonisCommand1,thesecondisCommand2,andsoon.
FIGURE18.9 Examplelistofcontrols
•ThePropertieslist.Thisisatwo-columnlistthatshowsallpropertiesassociatedwithaformorcontrolandtheircurrentsettings.Tochangeapropertiessettingthenthepropertiesnameisselectedandthenewsettingiseithertypedorselectedfromamenu.Propertiesthathavepredefinedsettings(suchasarangeofcoloursortrue/false)displaythelistofsettingsbyclickingthedownarrowattherightofthesettingsbox( ),ortheycanbecycledthroughbydouble-clickingthepropertynameintheleftcolumn.InFigure18.8theDefaultpropertyhaseitheraTrueorFalsesetting.A inthesecondcolumnindicateseithertheselectionofcoloursfromapaletteortheselectionofpicturefilesthroughadialogbox.
Figure 18.10 shows an example of colour settings. Note that the colourappearsasa24-bithexadecimalequivalent(with8otherattributebits),butwhentheuserselectsthecolouritappearsasacolourinthepalette.This24-bitcolourismadeuptored,greenandblue(RGB).Thestandardformatis:
FIGURE18.10 Settingcolour
TheRRhexadecimaldigitsgivethestrengthoftheredfrom00htoFFh(0to255), theGG hexadecimal digits give the strength of green andBB gives thestrength of blue. Thus for the colour strength parts:white is&HaaFFFFFF&,black is&?aa000000&, red is&Haa0000FF&, yellow is&Haa00FFFF& andcyanis&HaaFFFF00&.
18.7ControlsandEventControlshaveassociatedpropertiesandalsoanumberofevents.TheseeventscanbeviewedbydoubleclickingonacontrolorbyselectingViewCodefromProjectwindow.Figure18.11showsanexampleoftheCodewindows.Itcanbethat theobjectcanbeselectedbypullingdown themenuof the left-handsideandtheassociatedeventsintheright-handmenu.Theassociatedcodewiththatobjectandeventisshowninthewindowbelowthesemenuoptions.
FIGURE18.11 Selectingobjects
Figure18.12showsanexampleoftheeventsthatoccurwhenthecontrolisacommandbutton(inthiscasetheobjectisCommand1).Itcanbeseenthattheassociated events are: Click, DragDrop, DragOver, GotFocus, KeyDown,KeyPress and KeyUp. Each of these can have associated sections of code toreacttotheevent.Forexample,theClickeventisinitiatedwhentheuserclicksthemousebuttononthecommandbuttonandKeyDownisinitiatedwhenakeyhasbeenpresseddown.
FIGURE18.12 Eventswhenthecontrolisacommandbutton
18.8Exercises18.8.1.PlaceaCommandButtononaformanddisplayitsproperties.Noteallof
thepropertiesand,withthehelpofthehelpmanual,identifyofthefunctionofeachoftheproperties.Notethathelponapropertycanbe
foundbyhighlightingthepropertyandpressingF1.18.8.2.WithaCommandButtonidentifytheeventsthatareassociatedwithit.18.8.3.DeterminetheactualcoloursofthefollowingRGBcolourvalues:
(i)&H0080FF80&(ii)&H00FF8080&(ii)&H00C000C0&(iv)&H00E0E0E0&
18.8.4.Conductthefollowing:(i)Addacommandbuttontoaform.
(ii)ChangethetextontheCommandButtonto‘EXIT’.(iii)ChangethefontontheCommandButtonto‘TimesRoman’andthe
fontsizeto16.(iv)ResizetheCommandButtonsothatthetextfitscomfortablyintothe
button.(iv)Changethebackgroundcolouroftheformtoyellow.(v)ChangetheCaptionnameoftheformto‘MyApplication’.
18.8.5.DeveloptheformgiveninFigure18.13.
FIGURE18.13 Exercise
18.8.6.Explainwhy,inthepreviousexercise,thataradiobuttonisusedfortheageoptionandacheckboxisusedtoselectthechoicesofShowGraphicsandPlaySounds.Whichofthefollowingwouldberadiobuttonsorcheckboxes:(i)Itemsonashoppinglist.
(ii)Selectionofahorsetowinarace.
19
VisualBasicLanguage
19.1Introduction
This chapter discusses the Visual Basic language and how a program isdeveloped.
FIGURE19.5 IconsforMsgBox
19.2ProgramminglanguageVisualBasichasanexcellenton-linemanualinwhichtheusercaneithersearchfortheoccurrenceofkeywords(withHelp→SearchForHelpOn)orviewthecontents of themanual (Help→Contents). The left-hand side of Figure 19.1showsanexamplemanualpageaftertheuserhasselectedHelp→Contents→Visual Basic Help, and then leads to other parts of the manual, such as theProgrammingLanguageandContentsTopic.The left-handsideofFigure19.1showsanexampleoftheContentslist.
FIGURE19.1 VisualBasic4on-linehelpmanual
19.3EnteringaprogramTostartthedevelopmentofaprogramwithnocontrolsonaformthentheuserselects theViewCode from the Projectwindow. Figure 19.2 shows the basicsteps.AftertheViewCodeisselectedthentheuserselectstheFormobjectfromwithin the form codewindow.Next the code is entered between the PrivateSubLoad_From()andEndSub.Thiscodeisautomaticallyrunwhentheformisrun,astheprocedureisLoad.ThecodeinFigure19.2simplydisplaysthetext“Hellotoyou”toawindow.
FIGURE19.2 Stepstakentoentercode
19.4LanguagereferenceThissectioncontainsacondensedreferencetoVisualBasic.
19.4.1DataTypesAndDeclaringVariablesAvariableisdeclaredwiththeDimkeyword.Thesevariablesmustconformto
thefollowing:•Beginwithanalphabetcharacter.•Cannotcontainadot,‘$’,T,‘@’,‘#’or‘%’.•Mustbelessthan256characterslong.Examplesare:
whichdeclaresaBooleanvariablecalledval1,twosingleprecisionfloating-pointvariables:xandy,anintegernamedi,adatenamednewdateandastringof30charactersnamedname.Variablesareassignedvalueswiththeassignmentoperation(=),suchas:
whichsets theBooleanvariableval1toaTrue, thevalueofxto2.134,yto10.1, thedatenewdate isassigned thecurrentdate fromthe functionNowandthestringnameisassignedthestring“Fred”.Notethatstringsofcharactersaredefinedbetweeninvertedcommas(“”).
19.4.2OperatorsThebasicoperatorsinVisualBasicaresimilartotheonesusedinPascal.Table19.1showsthemainoperators.Theoperatorprecedenceis:
Table19.1Operatorprecedence
Arithmetic Comparison Logical
Exponentiation(^) Equality(=) Not
Negation(−) Inequality(<>)
Negation(−) Inequality(<>)And
Multiplicationanddivision(*,/) Lessthan(<) Or
Integerdivision(\) Greaterthan(>) Xor
Moduloarithmetic(Mod) LessthanorEqualto(<=)
Additionandsubtraction(+,–) GreaterthanorEqualto(>=)
Stringconcatenation(&)
•Arithmeticoperatorshavethehighestprecedence,followedbycomparisonoperatorsandfinallylogicaloperators.
•ArithmeticandlogicaloperatorsareevaluatedintheordergiveninTable19.1.
•Comparisonoperatorsallhaveequalprecedence.•Multiplicationanddivisionhavethesameprecedence,thentheoperationis
executedfromlefttoright.Thesameoccurswithadditionandsubtraction.
19.4.3DataTypesAswithCandPascal,VisualBasichasawholerangeofdatatypes.Theirrangedependsontheirformat(suchascharacters, integersandfloatingpointvalues)and the number of bytes used to store them. Table 19.2 outlines the mainpredefined(intrinsic)datatypes.AuserdefinedtypecanalsobedefinedusingtheTypestatement.
Table19.2Datatypes
Datatype Storagesize Range
Byte 1byte 0to255
Boolean 2bytes TrueorFalse
Integer 2bytes −32,768to32,767
Long(longinteger) 4bytes −2,147,483,648to2,147,483,647
Single(single-precisionfloating-point)
4bytes ±3.402823×1038to±1.401298×10−45
Double(double-precisionfloating-point)
8bytes ±4.94065645841247×10−324to±1.79769313486232×10308
Currency(scaledinteger) 8bytes ±922,337,203,685,477.5808
Date 8bytes January1,100toDecember31,9999.
String(variable-length) 10bytes+stringlength
0toapproximately2billion
19.4.4ConvertBetweenDataTypesVisual Basic has strong data type checking where the compiler generates anerrorwhenonedatatypeisassigneddirectlytoavariablewithanotherdatatype.Thusdifferentdatatypesmayneedtobeconvertedintoanothertypesothattheycanbeused.Thebasicconversionfunctionsare:
Cbool(expr) WhichconvertsanexpressionintoBoolean.Theexpressionargumentisanyvalidnumericorstringexpression.IfexpressioniszerothenaFalseisreturned,elseaTrueisreturned.
Cbyte(expr) WhichconvertsanexpressionintoByte.Theexpressionargumentisanyvalidnumericorstringexpression.IfexpressionliesoutsidetheacceptablerangefortheBytedatatypethenanerroroccurs.
Ccur(expr) WhichconvertsanexpressionintoCurrency.Theexpressionargumentisanyvalidnumericorstringexpression.IfexpressionliesoutsidetheacceptablerangefortheCurrencydatatypethenanerroroccurs.
Cdate(expr) WhichconvertsanexpressionintoDate.Thedateargumentisanyvaliddateexpression.
Cdbl(expr) WhichconvertsanexpressionintoDouble.Theexpressionargumentisanyvalidnumericorstringexpression.
Cint(expr) ConvertsanexpressiontoanInteger.Theexpressionargumentisanyvalidnumericorstringexpression.CintdiffersfromtheFixandIntfunctions,whichtruncate,ratherthanround,thefractionalpartofanumber.Whenthefractionalpartisexactly0.5,theCintfunctionalwaysroundsittothenearestevennumber.Forexample,0.5roundsto0,and1.5roundsto2.
Clng(expr) WhichconvertsanexpressionintoLong.Theexpressionargumentisanyvalidnumericorstringexpression.AswithCintthevalueisroundedtothenearestwholenumber.
Csng(expr) WhichconvertsanexpressionintoSingle.Theexpressionargumentisanyvalidnumericorstringexpression.IfexpressionliesoutsidetheacceptablerangefortheSingledatatype,anerroroccurs.
Cstr(expr) Whichconvertsanexpressionintostring.Theexpressionargumentisanyvalidnumericorstringexpression.IftheexpressionisBooleanthenastringisreturnedwitheitherTrueorFalse,elseanumericvaluereturnsastringcontainingthenumber.
lnt(expr)
Fix(expr) Returnstheintegerportionofanumber.IntdiffersfromFixinthatIntwhenthenumberisnegativethenitreturnsthefirstnegativeintegerwhichislessthanorequaltonumber,whereasFixreturnsthefirstnegativeintegergreaterthanorequaltonumber.Forexample,ifthevalueis–12.3thenIntconvertsthisto–13whileFixconvertsitto–12.
Atypicalconversionisfromanumericordatevariable intoastringformat.Program19.1showsanexampleofaVisualBasicprogramwhichcontainstheCStrfunctionwhichisusedtoconvertfromtwofloatingpointvalues(xandy),an integer (i) and date (newdate) into a string format. This is then used todisplay thevalues to awindowusing theMsgBox function.Theprogramalsouses theFix function to round-up thevalueofx.Figure19.3 showsa samplerun.
FIGURE19.3 SamplerunforProgram19.1
19.4.5Input/OutputThefunctionsthatcanbeusedtoinputandoutputinformationareInputBoxandMsgBox,respectively.Boththesefunctionsinputandoutputinformationintheformofastringofcharacters.Thuswhenoutputingnon-stringvariables,suchasintegersandfloating-pointvalues,theymustfirstbeconvertedtoastringusingoneofthestringconversionfunctions.Thesamemustbedoneforinput,wherethe input stringmustbe converted into the requireddata type, againusing thedatatypeconversionfunctions.
Output
TheMsgBoxfunctiondisplaysamessageinadialogboxwithspecifiedbuttonsand thenwaits for theuser to selectabutton.Thevalue returned indicates thechosenbutton.Thebasicformatis:
wheretheparametersinbracketsareoptional.Theparametersare:
prompt stringofbedisplayedinthedialogbox.
buttons Numericvaluethatisthesumofvaluesthatspecifiesthenumber,thetypeofbuttonstodisplay,theiconstyleandthedefaultbutton.Table19.3outlinesthesevaluesandifitisomittedthenthedefaultvalueforbuttonsis0.
title stringwhichcontainsthetitlebarofthedialogbox.Ifitisomittedthentheapplicationnameisplacedinthetitlebar.
helpfile stringthatidentifiestheHelpfiletousetoprovidecontext-sensitiveHelpforthedialogbox.Ifhelpfileisprovidedthencontextmustalsobeprovided.
context NumericvaluethatistheHelpcontextnumbertheHelpauthorassignedtotheappropriateHelptopic.Ifcontextisprovided,helpfilemustalsobeprovided.Whenbothhelpfileandcontextareprovided,theusercanpressF1toviewtheHelptopiccorrespondingtothecontext.
Table19.1definesthebuttonsettings.Thevaluesfrom0to5definethetypeofthebuttontobedisplayed.Forexample,avalueof5willhavetwobuttons,whichareRetryandCancel.Thevalues16,32,48and64identifytheicontobedisplayed.Forexample,avalueof32willdisplayaquestionbubble.The0,256and512definewhichbutton is thedefault.Eachof thesevaluescanbeaddedtogether to create the requires set of buttons, icon and default button. Forexample,tocreateadialogboxwiththeOKandCancelbuttons,aCriticaliconandtheCancelbuttontobethedefault,thenthesettingwouldbe:
Table19.3Buttonsettings
Constant Value Description
vbOKOnly 0 DisplayOKbuttononly
vbOKCancel 1 DisplayOKandCancelbuttons.Seeexample1inFigure19.4.
vbAbortRetryIgnore 2 DisplayAbort,Retry,andIgnorebuttons.Seeexample2inFigure19.4.
vbYesNoCancel 3 DisplayYes,No,andCancelbuttons.Seeexample3inFigure19.4.
vbYesNo 4 DisplayYesandNobuttons.Seeexample4inFigure19.4.
vbRetryCancel 5 DisplayRetryandCancelbuttons.Seeexample5inFigure19.4.
16
vbCritical16
DisplayCriticalMessageicon.Seeexample1inFigure19.5.
vbQuestion 32 DisplayWarningQueryicon.Seeexample2inFigure19.5.
vbExclamation 48 DisplayWarningMessageicon.Seeexample3inFigure19.5.
vbInformation 64 DisplayInformationMessageicon.Seeexample4inFigure19.5.
vbDefaultButton1 0 Firstbuttonisdefault
vbDefaultButton2 256 Secondbuttonisdefault
vbDefaultButton3 512 Thirdbuttonisdefault
which is 273. Note that to aid documentation in the program then thepredefinedconstantvaluescanbeused,soforthepreviousexample:
TheMsgBoxfunctionreturnsavaluedependingonthebuttonpressed;thesereturnvaluesareoutlinedinTable19.4.Forexample,iftheuserpressestheOKbuttonthenthereturnvaluewillbe1.IfthedialogboxhasaCancelbuttonthentheuserpressingESChasthesameeffectaschoosingCancel.Ifthedialogboxcontains aHelp button, context-sensitiveHelp is provided for the dialog box.However,novalueisreturneduntiloneoftheotherbuttonsischosen.
Table19.4MsgBoxreturnvalues
Constant Value Buttonchosen
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vblgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
Program19.2givesanexampleofaprogramwhichdisplaysadialogboxwithYesandNobuttons,andaquestionmarkicon.Theresponsewillthuseitherbea6(iftheYesbuttonisselected)ora7(iftheNobuttonisselected).Figure19.6
showsasamplerun.
FIGURE19.6 Examplerun
InputTheInputBoxfunctionpromptstheusertoinputtext,orchooseabutton.Itthenreturnsthecontentsofthetextbox.Thebasicformatis:
wheretheparametersinbracketsareoptional.Theparametersare:
prompt stringofbedisplayedinthedialogbox.
title stringwhichcontainsthetitlebarofthedialogbox.Ifitisomittedthentheapplicationnameisplacedinthetitlebar.
inthetitlebar.
default stringwhichisdisplayedinthetextboxandisthedefaultresponseifnootherinputisprovided.Ifthisfieldisomittedthenthetextboxisinitiallyempty.
xpos Numericvaluethatspecifies(intwips)thehorizontaldistanceoftheleftedgeofthedialogboxfromtheleftedgeofthescreen.Ifxposisomittedthenthedialogboxishorizontallycentred.
ypos Numericvaluethatspecifies(intwips)theverticaldistanceoftheupperedgeofthedialogboxfromthetopofthescreen.Ifyposisomittedthenthedialogboxisverticallypositionedapproximatelyone-thirdofthewaydownthescreen.
helpfile stringthatidentifiestheHelpfiletousetoprovidecontext-sensitiveHelpforthedialogbox.Ifhelpfileisprovidedthencontextmustalsobeprovided.
context NumericvaluethatistheHelpcontextnumbertheHelpauthorassignedtotheappropriateHelptopic.Ifcontextisprovided,helpfilemustalsobeprovided.Whenbothhelpfileandcontextareprovided,theusercanpressF1toviewtheHelptopiccorrespondingtothecontext.
Program19.3showsanexampleusageoftheInputBoxfunction.Inthiscasethemessage for the title is ‘Inputdemonstration’, thedefaultvalue is ‘10’andthevalueisreturnintotheinvalvariable.
FIGURE19.7 Examplerun
19.4.6DecisionsAndLoopsThedecisionsand loops inVisualBasicare similar to theonesused inCandPascal.
IfstatementThebasicifstatementformatis:
or,ingeneral:
Where the conditioncanbeanumericor stringexpression that evaluates toTrueorFalse.Thestatementblockcontainsoneormorestatementsseparatedbycolons.AswithC and Pascal, if the first condition is True then the first statement
blockisexecuted,elseifthesecondconditionisTruethenthesecondstatementblock is executed, and soon. Ifnoneof the conditions areTrue then the finalelsestatementblockisexecuted(ifitexists).Note thatElse andElseIf arebothoptional and there canbeanynumberof
Elself clauses but none of them can occur after the Else clause Program 19.4givesanexampleofaprograminwhichtheuserentersavaluefrom0to2andtheprogramdisplaystheequivalentresistorcolourcodecolour.
CaseTheCasestatement issimilar to thecaseandswitchstatementsused inPascalandC.Itsgeneralformis:
The expression can be any numeric or string expression. A match of theexpressiontotheexpressionvaluecausesthecorrespondingstatementblocktobeexecuted. Ifnoneof theblockmatch then theCaseElse statementblock isexecuted. If testexpression matches any expressionlist expression associatedwithaCaseclause,thestatementsfollowingthatCaseclauseareexecuteduptothenextCaseclause,or, for the lastclause,up to theEndSelect.Control thenpasses to the statement following End Select. If testexpression matches anexpressionlist expression in more than one Case clause, only the statementsfollowingthefirstmatchareexecuted.MultipleexpressionsorrangescanbeaddedtotheCasecause,suchas:
It isalsopossible tospecifyrangesandmultipleexpressionsforstrings.Forexample the following matches the string to ‘apple’ and everything,alphabeticallybetween,‘banana’and‘carrot’:
Program 19.5 shows an example of a programwhich is similar to Program19.4butusesacasestatementtoselecttheresistorcolourcodecolour.
ForloopTheForloopissimilartotheforloopinPascal.Itrepeatsagroupofstatementsanumberoftimes.Itsgeneralformis:
or
Wherecounterisanumericvariablewhichasusedaloopcounter,startistheInitialvalueofcounter,endisthefinalvalueofcounterandstepistheamountbywhichthecountischangedforeachloop.Thisvaluecaneitherbepositiveornegative.Thedefaultstepsize,ifnotspecifiedis1.Program 19.6 uses a for loop to calculate the factorial value of an entered
value.
FIGURE19.8 Examplerun
Do..whileloopTheDo..whileloopissimilartothewhile()statementsusedinPascalandC.Itsgeneralformis:
or
or
or
Program19.7usesado..whilelooptotesttoseeiftheuserinputiswithinavalidrange.Inthiscasethevalidinputisbetween0and10forthevoltageinputandgreater than0andupto10for thecurrent input.If theuserentersavaluewhich isoutside this range thenaMsgBox isdisplayedwithanerrormessage(INVALID:re-enter).
19.5Exercises19.5.1.CompleteProgram19.5sothatitimplementsthecompleteresistor
colourcode(seeTable6.1onpage117).19.5.2.Changetheprogramin19.5.1sothatitloopsuntiltheuserentersavalid
value(between0and9).19.5.3.Changetheprogramin19.5.2sothataftertheresulthasbeendisplayed
theuserispromptedastowhethertorepeattheprogram(OK)orexittheprogram(Cancel).
19.5.4.Writeaprogramwhichwillcontinuallydisplaythecurrentdateandtime.Thesamplecodegivenbelowdisplaysasingledateandtime.
19.5.5.ModifytheprograminExercise19.5.4sothattheOKandCancelbuttonsareshown.IftheuserselectstheCancelbuttonthentheprogramshouldexit,elsetheprogramshoulddisplaythenewdate.Thesample
codegivenbelowdisplaysasingledateandtimewiththeOKandCancelbuttons.
19.5.6.CompleteWorksheet2onpage37usingVisualBasic.NotethatforW2.2thesquarerootfunctioninVisualBasicissqr,andinW2.3theinversetangentfunctionisatn.
20
Forms
20.1Introduction
This chapter discusses how forms are constructed and how code is associatedwiththeform.
20.2SettingpropertiesEachcontrolobjecthasasetofpropertiesassociatedwith it.Forexample, theTextBoxcontrolinFigure20.1hasanobjectnameofText1.Thisobjecthasanumber of associated properties, such as Alignment, Appearance, BackColor,andsoon.Thesepropertiescanbechangedwithintheprogrambyusingthedotnotation.Forexample,tochangethefontto‘CourierNew’,thetextdisplayedintheobjectto‘Hello’andtheheightofthewindowto1000thefollowingcanbeused:
FIGURE20.1 Objectproperties
20.3FormsandcodeVisualBasicprogramsarenormallydesignedbyfirstdefiningtheuserinterface(the form) andwriting the codewhich is associatedwith events and controls.Thebestwaytoillustratetheprocessiswithanexample.
20.3.1MultipleChoiceExampleIn this example the user is to design a formwith a simple question and threeoptionalexamples. It shoulddisplay if theanswer iscorrect (TRUE)orwrong(FALSE).Theprogramshouldcontinueaftereachselectionuntiltheuserselectsanexitbutton.
Step1:Thelabelcontrolisselected Thenthetext‘WhatisthecapitalofFrance’isenteredthecaptionfield,asshowninFigure20.2.
FIGURE20.2 Step1
Step2:
Nexttheuseraddacommandbuttonbyselectingthecommandcontrol .The button is then added to the form and the Caption property is set to
‘Edinburgh’,asshowninFigure20.3.
FIGURE20.3 Step2
Step3:Next the user adds another command button by selecting the command
control.ThebuttonisthenaddedtotheformandtheCaptionpropertyissetto‘Paris’,asshowninFigure20.4.
FIGURE20.4 Step3
Step4:Next the user adds another command button by selecting the command
control.ThebuttonisthenaddedtotheformandtheCaptionpropertyissetto‘Munich’,asshowninFigure20.5.
FIGURE20.5 Step4
Step5:
NexttheuseraddsaTextBox .Thisisthenaddedtotheright-handsideoftheform,asshowninFigure20.6.TheTextpropertyisthenchangedtohaveanemptyfield.TheTextBoxwillbeusedtodisplaytextfromtheprogram.
FIGURE20.6 Step5
Step6:Next the user adds another command button by selecting the command
control.ThebuttonisthenaddedtotheformandtheCaptionpropertyissetto‘Exit’,asshown inFigure20.7.Acharacter in thenamecanbeunderlinedbyputtingan&beforeit.Thus‘&Exit’willbedisplayedas‘Exit’.
FIGURE20.7 Step6
Step7:Nextthecodecanbeattachedtoeachofthecommandbuttons.Thisisdone
byeitherdoubleclickingonthecommandbuttonorbyselectingthebuttonandpressing theF7key.Todisplay to theTextBox (theobjectnamedText1) thenthetextpropertyissetwith:
whichdisplaythestring“FALSE”tothetextwindow.TheassociatedcodeisshowninFigure20.8.
FIGURE20.8 VisualBasic4on-linehelpmanual
Step8:Nextthecodeassociatedwiththesecondcommandbuttonisset,with:
asshowninFigure20.9.
FIGURE20.9 VisualBasic4on-linehelpmanual
Step9:Nextthecodeassociatedwiththethirdcommandbuttonisset,with:
asshowninFigure20.10.
FIGURE20.10 VisualBasic4on-linehelpmanual
Step10:Finallythecodeassociatedwiththeexitcommandbuttonissetbyaddingthe
code:
whichcausestheprogramtoendandthecodeisshowninFigure20.11.
FIGURE20.11 VisualBasic4on-linehelpmanual
The program can then be executed with Run→Start. Figure 20.12 shows asamplerun.
FIGURE20.12 Sampletestrun
NexttheformandtheprojectaresavedusingtheFile→Saveoption.Ifthefilehasnotbeensavedbeforethentheuserwillbepromptedtogivetheprojectandthe form a new file name. In this case save the project and the form asVB03_01.VBPandVB03_01.FRM.ThesearelistedinProgram20.1.Itcanbeseenthat theformfile(VB03_01.FRM)containstheVisualBasiccodealongwiththepropertiesanddefinitionsofthecontrols,whereastheprojectfile(VB03_01.VBP)definestheuser’senvironment,suchas:•Thenamesofanyforms.•Thecontroltypes.
20.4TemperatureconversionprogramIn this example the user will enter either a temperature in Centigrade orFahrenheit and the program will convert to an equivalent Fahrenheit orCentigradetemperature.Thestepstaken,withreferencetoFigure20.13,are:
FIGURE20.13 Temperatureconversionform
1.AddaLabelcontrolandchangeitsCaptionpropertyto‘Centigrade’.2.AddaLabelcontrolandchangeitsCaptionpropertyto‘Fahrenheit’.3.AddaTextBoxcontrolandputitbesidetheCentigradeLabel.Next
changeitsTextpropertyto‘0’.4.AddaTextBoxcontrolandputitbesidetheFahrenheitLabel.Next
changeitsTextpropertyto‘32’.5.AddaCommandButtoncontrolandputitbelowthetextboxes.Next
changeitsCaptionpropertyto‘CtoF’.ThiscommandbuttonwillconvertthevalueintheCentigradetoFahrenheitandputtheresultintheFahrenheittextbox.
6.AddaCommandButtoncontrolandputitbesidetheothercommandbutton.NextchangeitsCaptionpropertyto‘FtoC’.ThiscommandbuttonwillconvertthevalueintheFahrenheittoCentigradeandputtheresultintheCentigradetextbox.
7.SelecttheformandchangetheCaptionpropertyto‘TemperatureConversion’.
Nextthecodeassociatedwitheachcontrolcanbeadded,asfollows:1.Firstaddcodetothefirstcommandbutton(CtoF)whichwillbeusedto
convertthetextfromtheCentigradetextbox(Text1)anddisplayittotheFahrenheittextbox(Text2).Thisisachievedwith:
2.Nextaddcodetothesecondcommandbutton(FtoC)whichwillbeusedtoconvertthetextfromtheFahrenheittextbox(Text2)anddisplayittotheCentigradetextbox(Text1).Thisisachievedwith:
AtestrunoftheprogramisgiveninFigure20.14.
FIGURE20.14 Samplerun
Thetemperatureconversionprogramuptothispointhasseveralweaknesses.One of these is that it does not have an exit option (this will be left as anexercise) and the other is that the user can enter a valuewhich is not a validtemperaturevalueandtheprogramwillacceptit.Forexample,iftheuserentersastringofcharactersthentheprogramstopsanddisplaysthemessageshowninFigure20.15.
FIGURE20.15 Samplerunwithinvalidinput
Toovercome thisproblem thevalue that is entered is tested to see if it is avalidnumericvalue,usingtheIsNumeric()function.ThisreturnsaTRUEifthevaluecanbeconvertedtoanumericvalue,elseaFALSE.Themodifiedcodeforthe two command buttons is given next and a sample run is shown in Figure20.16.
FIGURE20.16 Samplerunwithinvalidinput
20.5QuadraticrootsprogramInthisexampletheprogramcalculates therootsofaquadraticequationwithauserenteredvaluesofa,bandc.Thegeneralformofaquadraticequationis:
thegeneralsolutionis:
Thisleadstothreetypesofroots,theseare:if(b2>4ac)thentherearetworealroots;elseif(b2=4ac)thenthereisasinglerootof–b/4a;elseif(b2<4ac)thenthesearetwocomplexrootswhichare:
Thestepstaken,withreferencetoFigure20.17,are:
FIGURE20.17 Quadraticequationform
1.AddaLabelcontrolandchangeitsCaptionpropertyto‘a’.2.AddaLabelcontrolandchangeitsCaptionpropertyto‘b’.3.AddaLabelcontrolandchangeitsCaptionpropertyto‘c’.4.AddaLabelcontrolandchangeitsCaptionpropertyto‘x1’.5.AddaLabelcontrolandchangeitsCaptionpropertyto‘x2’.6.AddaTextBoxcontrolandputitbesidetheaLabel.NextchangeitsText
propertyto‘0’(thisistheText1object).7.AddaTextBoxcontrolandputitbesidethebLabel.NextchangeitsText
propertyto‘0’(thisistheText2object).8.AddaTextBoxcontrolandputitbesidethecLabel.NextchangeitsText
propertyto‘0’(thisistheText3object).9.AddaTextBoxcontrolandputitbesidethex1Label.Nextchangeits
Textpropertyto‘0’(thisistheText4object).10.AddaTextBoxcontrolandputitbesidethex2Label.Nextchangeits
Textpropertyto‘0’(thisistheText5object).11.AddaCommandButtoncontrolandputitbelowthetextboxes.Next
changeitsCaptionpropertyto‘Calculate’.Thiscommandbuttonwillbeusedtodeterminetherootsoftheequation.
12.AddaCommandButtoncontrolandputitbesidetheothercommandbutton.NextchangeitsCaptionpropertyto‘Exit’.Thiscommandbuttonwillbeusedtoexittheprogram.
13.SelecttheformandchangetheCaptionpropertyto‘QuadraticEquation’.Nextthecodeassociatedwitheachcontrolcanbeadded,asfollows:1.Firstaddcodetothefirstcommandbutton(Calculate)whichwillbeused
tocalculatetherootsanddisplaytotherootstextbox(Text4andText5).Thisisachievedwith:
Noticethatthecodeincludesthe_characterwhichallowstheprogrammertocontinueastatementontoanotherline.
2.Nextaddcodetothesecondcommandbutton(Exit):
Figure20.18showstwosampleruns.
FIGURE20.18 Sampleruns
20.6ResistancecalculationwithslidercontrolsprogramAnexcellentmethodofallowingtheusertoinputavaluewithinafixedrangeistouseaslidercontrol.Theseslidercontrolscaneitherbevertical (VScroll)orhorizontal(HScroll).Themainproperties,asshowninFigure20.19,ofascrollbarare:
FIGURE20.19 Scrollbarproperties
•Max.Whichdefinesthemaximumvalueofthescrollbar.•Min.Whichdefinestheminimumvalueofthescrollbar.•Value.Whichgivesthecurrentslidervalue.
Asanexample,ahorizontalsliderwillbesetupwithavoltagerangeof0to100.Thevalueof the sliderwill be shown.The steps taken,with reference toFigure20.20,are:
FIGURE20.20 Voltageform
1.AddaLabelcontrolandchangeitsCaptionpropertyto‘Voltage’.2.AddaLabelcontrolandchangeitsCaptionpropertyto‘0’.3.AddaHScrollBarcontrolbelowthelabels.NextchangeitsMaxproperty
to‘100’anditsMinpropertyto‘0’.Nextthecodeassociatedwitheachcontrolcanbeadded,asfollows:1.Addcodetothehorizontalscrollbarwhichwillbeusedtodisplayits
valuetothevoltagevaluelabel(Label2).Thisisachievedwith:
Thiswill take thevalue from the scroll bar (HScroll1.Value) anddisplay tothesecondlabelbox(Label2).Whentheprogramisrunthentheusercanmovethescrollbarbackandforwardwhichcausesachangeinthedisplayedvoltagevalue(from0to100).AsamplerunisshowninFigure20.21.
FIGURE20.21 Samplerun
This project can now be enhanced by adding another slider for current anddisplaying theequivalent resistance (which isvoltagedividedbycurrent).Thestepstaken,withreferencetoFigure20.22,are:
FIGURE20.22 Newform
1.AddaLabelcontrolandchangeitsCaptionpropertyto‘Voltage’.2.AddaLabelcontrolandchangeitsCaptionpropertyto‘0’.3.AddaHScrollBarcontrolbelowthelabels(HScrolll).Nextchangeits
Maxpropertyto‘100’anditsMinpropertyto‘0’.4.AddaLabelcontrolandchangeitsCaptionpropertyto‘Current’.5.AddaLabelcontrolandchangeitsCaptionpropertyto‘0’.6.AddaHScrollBarcontrolbelowthelabels(HScroll2).Nextchangeits
Maxpropertyto‘100’anditsMinpropertyto‘0’.7.AddaLabelcontrolandchangeitsCaptionpropertyto‘Resistance’.8.AddaLabelcontrolandchangeitsCaptionpropertyto‘0’.
Nextthecodeassociatedwitheachcontrolcanbeadded,asfollows:1.Addcodetothefirsthorizontalscrollbar(HScrolll)whichwillbeusedto
displayitsvaluetothevoltagevaluelabel(Label2).Theresistancelabel(Label6)isalsoupdatedwiththeresultofthevoltagedividedbythecurrent.Thisisachievedwith:
2.Addcodetothesecondhorizontalscrollbar(HScroll2)whichwillbeusedtodisplayitsvaluetothecurrentvaluelabel(Label4)withthevalueofthescrollbardividedby100.Theresistancelabel(Label6)isalsoupdatedwiththeresultofthevoltagedividedbythecurrent.Thisisachievedwith:
Figure20.23showsasamplerun.
FIGURE20.23 Samplerun
Oneof theproblemsof thedesign is that thecontrolsandformhavenameswhichdonotdocument their function.VisualBasicusesanamingconventionwhichusesthetypeofcontrolandconsecutivelyaddsanumber,asshowninthedesigninFigure20.24.
FIGURE20.24 Objectnames
Inthiscaseanimprovednamingconventionmightbe:
These are set by selecting the properties of each of the objects and thenchangingtheNamepropertytotherequiredname.AnexampleofchangingthenameoftheformtoResistance_CalcisgiveninFigure20.25.
FIGURE20.25 Changingthenameoftheform
Figure 20.26 shows the list of objects after each of their names has beenchanged.Noticethatitisnoweasiertolocatetherequiredobject.
FIGURE20.26 Changingthenameoftheform
Nextthecodemustbemodifiedsothatthereferencesaretothenewlynamedobjects.Thecodeforthevoltagescrollbar(Voltage_Value)isnow:
andthecodeforthecurrentscrollbar(Current_Value)isnow:
20.7Exercises20.7.1.WriteaVisualBasicprograminwhichtheuserenterseitheravaluein
eitherradiansordegreesandtheprogramconvertstoeitherdegreesorradians,respectively.Figure20.27showsasamplerun.
FIGURE20.27 Radianstodegreesconversion
20.7.2.ModifytheprograminExercise20.7.1sothatinvalidentriesarenotaccepted.
20.7.3.ModifytheprograminExercise20.7.2sothattheconversionvalueisautomaticallyconvertedwhentheuserentersavalue(thatis,thereisnoneedforthecommandbuttons).
20.7.4.WriteseparateVisualBasicprogramswithslidercontrolsforthefollowingformula:(i)F=marange:m=0.01to1000g,a=0.01to100m.s−2
(ii)V=IRrange:1=0.1to100A,V=0.1to100V20.7.5.WriteaVisualBasicprogramthatcalculatesthevaluesofmandcfora
straightline.Thevaluesof(x1,y1)and(x2,y2)shouldbegeneratedwithslidercontrols(witharangeof–100to+100foreachofthevalues).Figure20.28showsasampledesign.
FIGURE20.28 Straightlineprogramdesign
20.7.6.ModifytheprograminExercise20.7.5sothatadividebyzerodoesnotoccurwhenthedifferenceinthexvaluesiszero.Ifthisissothentheprogramshoulddisplay‘INFINITY’forthegradient.Ifthetwocoordinatesarethesamethentheprogramshoulddisplaythemessage‘INVALID’forthegradient.
20.7.7.WriteaVisualBasicprogramwhichhasamultiplechoiceoptionquestionwhichisrepeated.Theprogramshouldkeeparunningtallyofthenumberofcorrectanswersandthenumberofincorrectanswers.
20.7.8.CompleteWorksheet3onpage39usingVisualBasic.
21
MenusandDialogBoxes
21.1Introduction
Thischapterdiscusseshowmenusanddialogboxesareused.
21.2MenueditorMostWindowsprogramshavemenusinwhichtheuserselectsfromarangeofdefinedpull-downmenuswithdefinedoptions.VisualBasichasaneasy-to-usefunction called the Menu Editor which is used to create custom menus. The
MenuEditorisstartedfromtheToolsMenuorfromthetoolbarshortcut .AnexamplescreenfromtheMenuEditorisshowninFigure21.1.Itincludes:
FIGURE21.1 Menueditor
•Caption.Whichisatextboxinwhichthenameofthemenubarormenuoptionisentered.Ahyphen(-)isenteredasacaptionifamenuseparatorbarisrequired.Thisbarhelpstoseparatemenuoptions.OfteninmenustheusercanselectamenuoptionbypressingtheALTkeyandanassignedkey(hotkey).TospecifytheALT-hotkeythenan&isinsertedbeforetheletterofthemenuoption.Whentheprogramisrunthenthisletterisunderlined.ForexampleFi&lewouldbedisplayedasFileandtheassignedkeyswouldbeALT-L.Adoubleampersandspecifiestheampersandcharacter.
•Name.Whichisatextboxinwhichthecontrolnameforthemenuoptionisspecified.Thisisusedbytheprogramcodeandisnotdisplayedtotheuserwhentheprogramisrun.
•Index.Whichisanumericvaluethatcanbeusedtospecifythemenuoption.Typicallyitisusedwhencallingasinglefunctionwhichservicesseveralmenuitems.Forexample,aFilemenumayhavetheoptions:New,OpenandSave,thenasinglefunctioncouldbecreatedtoservicetheserequestsandtheindexvaluewouldbeusedwhichoptionhasbeenselected.
•Shortcut.Whichisapull-downmenuthatcanbeusedtospecifyashortcutkey(Cntrl-AtoCntrl-Z,F1toF12,Cntrl-F1toCntrl-F12,Shift-F1toShift-F12,Shift-Cntrl-F1toShift-Cntrl-F12,Cntrl-Ins,Shift-Ins,Del,Shift-Del,Alt-Bkspace).
•HelpContextlD.WhichisatextboxinwhichauniquenumericvalueisspecifiedforthecontextID.ThisvaluecanbeusedtofindtheappropriateHelptopicintheHelpfileidentifiedbytheHelpFileproperty.
•NegotiatePosition.Whichisapull-downlistboxwhichallowstheusertospecifythemenu’sNegotiatePositionpropertyanddeterminehowthemenuappearsinaform.Valueoptionsare0(None),1(Left)and2(Middle)and3(Right).
•Checked.Whichisacheckboxwhichspecifiesifacheckmarkistoappearinitiallyattheleftofamenuitem.Itisgenerallyusedtospecifyifatoggledmenuoptionisinitiallyonoroff.
•Enabled.Whichisacheckboxwhichspecifiesifthemenuitemistorespondtoevents.Ifitisnotenabledthenthemenuitemappearsdimmed.
•Visible.Whichisacheckboxwhichspecifiesifthemenuitemistoappearinthemenu.
21.2.1CreatingAMenuSystemThe user enters the caption and name and then uses the outlining buttons toeitherpromoteordemote the itemtoahigheror lower level (with the leftandrightarrowbuttons)orupanddown(withtheupanddownarrowbuttons).Withthisupto4levelsofsubmenuscanbecreated.Thelistboxdisplaysahierarchicallistofmenuitemswithindentedsubmenu
itemswhichindicatetheirhierarchicalposition.AmenuoptionisinsertedusingtheInsertbuttonanddeletedwith theDeletebutton.TheOKbuttoncloses theMenuEditorandsavesthemostrecentchanges.Thecodeassociatedwithamenuitemisdefinedbythemenuitemname.For
exampleifamenuitemhasthecaptionofFileandanameofFileOptionthentheassociatedcodefunctionwillbeFileOption_Click.Forexample,tocreateamenuwith:
1.Createacaption&FileandaddthenameofMenuFile.NextpresstheNextbutton.
2.Createacaption&OpenandaddthenameofMenuFileItem.Addanindexvalueof0.Thenselecttherightarrowbuttontomovetheoptiontothenextlevel,asshowninFigure21.2.NextpresstheNextbutton.
FIGURE21.2 Addingamenuitem
3.Createacaption&SaveandaddthenameofMenuFileItem.Addanindexvalueof1,asshowninFigure21.3.NextpresstheNextbutton.
FIGURE21.3 Addingamenuoption
4.Createacaption&CloseandaddthenameofMenuFileItem.Addanindexvalueof2,asshowninFigure21.4.NextpresstheNextbutton.
FIGURE21.4 Addingamenuoption
5.Createacaption&ExitandaddthenameofExit.Thenselecttheleftarrowbuttontomovetheoptiontothenextlevel,asshowninFigure21.5.NextpresstheOKbuttonandtheformshowninFigure21.6shouldbedisplayed.
FIGURE21.5 Addingamenuoption
FIGURE21.6 Menueditor
The associated code modules which are related to these menus items areMenuFile_Click(), MenuFileItem_Click() and Exit_Click(). TheMenuFileItemClick()modulehastheIndexparameterpassedtoit.Thishasavalueof0whenOpenisselect,a1whenSaveisselectedanda2whenCloseisselected.TheMenuFileItemisspecifiedwith:
thusthevalueofIndexwilleitherbe0,1or2.Next a textbox is added to the form (Text1), as shown inFigure21.7.The
resultingobjectsareshowninFigure21.8.
FIGURE21.7 Addingtextbox
FIGURE21.8 Programobjects
Next the code can be added. The MenuFileItem object services the Open,SaveandCloseoptionsandtheIndexparameterpassedintoit.InthecodebelowtheCasestatementisusedtotesttheIndexparameterand,inthiscase,displaysometexttothetextbox.
This code appends either ‘Open’, ‘Save’ or ‘Close’ to the text box (Text1).The&characterconcatenatestwostringstogether, thusthecodeText1.Text&“Open”simplyaddsthetext‘Open’tothetextalreadyinthetextwindow.Theexitcodeisaddedasfollows:
Figure 21.9 shows a sample run of the developed program. The Exitmenuoption is used toquit theprogramand theFile options (File,Save andClose)simplydisplaytherequiredtexttothetextbox.
FIGURE21.9 Examplerun
21.3CommondialogcontrolTheCommonDialogcontrolallowsforfileoperationssuchasopening,savingorprinting files. It is basically a control betweenVisualBasic and theMicrosoftWindows dynamic-link library COMMDLG. DLL. Thus this file must be in theMicrosoftWindowsSYSTEMdirectoryforthecommondialogcontroltowork.Adialog box is added to an application by first adding theCommonDialog
control to a form and setting its properties.Whendeveloping the program thecommon dialog box is displayed as an icon on the form.A program calls thedialog with one of the following (assuming that the dialog box is namedCommonDialog1): CommonDialog1.Filter A string which displays thefilenamefilter.The|characterisusedtodifferentiatedifferentForexamplethefollowingfilterenables theuser toselect text filesorgraphicfiles that includebitmapsandicons:
CommonDialog1.FilenameWhichreturnsorsetsthepathandfilenameofaselectedfile.CommonDialog1.FilterlndexWhichdefinesthedefaultfilter(withreference
totheFilter).CommonDialog1.ShowSaveWhichreturnsorsetsthepathandfilenameofa
selected file. Displays the CommonDialog control’s Save As dialog box. TheobjectplaceholderrepresentsanobjectexpressionthatevaluatestoanobjectintheAppliesTolist.CommonDialog1.ShowOpen Which displays the CommonDialog control’s
Opendialogbox.CommonDialog1.ShowPrinterWhichdisplaystheCommonDialogcontrol’s
Printerdialogbox.CommonDialog1.ShowFont Which displays the CommonDialog control’s
Fontdialogbox.CommonDialog1.ShowHelp Which runsWINHELP.EXE and displays the
specifiedhelpfile.Adialogbox is added to a form in anyposition, as shown inFigure21.10.
Thisboxcanbeplacedanywhere as itwill notbe seenon the formwhen theprogramisrun.
FIGURE21.10 Examplerun
Thecommondialogboxcanbeusedtodeterminethefilenameofafiletobeopenedorsaved.ItisusedinProgram21.3(whichisamodificationofProgram21.1)intheOpenandSavefilemenuoptions.Thefilterissetto:
This displays, in the Type of File field, the three options “All Files
(*.*),*.*,Text Files (*.txt),*.txt and Temp Files (*.tmp) |*.tmp”.Thedefaultfiletypeissettothesecondoptionwiththefilterindexsettingof:
Figure21.11showsasamplerunandthedialogbox.Itcanbeseen that thedefaultTypeofFileissetto“TextFiles(*.txt)”andFigure21.12showsanexamplemessagebox.
21.3.1FileOpen/SaveDialogBoxFlagsVariousflagscanbesetbeforethefileopen/savedialogbox.ThesearedefinedinTable21.1aresetwith:
Table21.1CommonDialogcontrolconstants
Constant Value Description
cdlOFNReadOnly &H1(1) ChecksReadOnlycheckboxforOpenandSaveAsdialogboxes,seeFigure21.13.
cdlOFNOverwritePrompt &H2(2) CausestheSaveAsdialogboxtogenerateamessageboxiftheselectedfilealreadyexists.
cdlOFNHideReadOnly &H4(4) HidestheReadOnlycheckbox,seeFigure21.14.
cdlOFNNoChangeDir &H8(8) Setsthecurrentdirectorytowhatitwaswhenthedialogboxwasinvoked.
cdlOFNHelpButton &H10(16) CausesthedialogboxtodisplaytheHelpbutton.
cdlOFNNoValidate &H100(256)
Allowsinvalidcharactersinthereturnedfilename.
cdlOFNAllowMultiselect &H200(512)
AllowstheFileNamelistboxtohavemultipleselections,seeFigure21.15.
cdlOFNExtensionDifferent &H400(1024)
TheextensionofthereturnedfilenameisdifferentfromtheextensionsetbytheDefaultExtproperty.
cdlOFNPathMustExist &H800(2096)
Usercanenteronlyvalidpathnames.
cdlOFNFileMustExist &H1000(4096)
Usercanenteronlynamesofexistingfiles.
The flags can either be defined with their constant name (such ascdlOFNReadonly)orby thevalue (0x01).Thesevaluesornamescanbeaddedtogether to achieve the required functionality. For example, modifying the
previous example to checks the read-only check box for Open dialog box. AsampledialogboxisshowninFigure21.13.
FIGURE21.13 Examplerun
For example, modifying the previous example to hide the read-only checkbox.AsampledialogboxisshowninFigure21.14.
FIGURE21.14 Examplerun
For example,modifying the previous example toAllows theFileName listboxtohavemultipleselections.AsampledialogboxisshowninFigure21.15.
FIGURE21.15 Examplerun
Theflagsettingsforadialogboxwiththeread-onlyboxcheckingandthattheuserisnotallowedtochangethedirectorycaneitherbesetwith:
which is1 (cdlOFNReadonly)added to8 (cdlOFNNochangeDir).Themethodofusinglableconstantsispreferableasithelpstodocumenttheprogram.
21.3.2ShowingHelpManualsThecommondialogboxcanalsobeusedtorunthehelpprogramWINHELP.EXE.Thisisachievedby:
andthenameofthehelpmanualisspecifiedby:
Variousoptionsflagscanalsobesetwiththehelpoption,thesearespecifiedinTable21.2.
Table21.2CommonDialogcontrolconstants
Constant Value Description
cdlHelpCommand &H102 Executesahelpmacro.
cdlHelpContents &H3 Displaysthehelpcontentstopic.
cdlHelpContext &H1 Displayshelpforaparticularcontext.
cdlHelpContextPopup &H8 Displaysinapop-upwindowaparticularHelptopic.
cdlHelpForceFile &H9 EnsuresthatWinHelpdisplaysthecorrectHelpfile.IfthecorrectHelpfileiscurrentlydisplayed,noactionoccurs.IftheincorrectHelpfileisdisplayed,WinHelpopensthecorrectfile.
cdlHelpHelpOnHelp &H4 DisplaysHelpforusingthehelpapplicationitself.
cdlHelpIndex &H3 DisplaystheindexofthespecifiedHelpfile.
cdlHelpKey &H101 DisplaysHelpforaparticularkeyword.
Typicallyahelpmenuoptionisaddedtoaprogram.Anexamplehelpeventisgiven in Program 21.4. The help command used is cdlHelpConents whichshowstheindexpageofthehelpmanual.Figure21.16showsanexampleofarun and Figure 21.17 shows an example for the An example of Vbcbt helpmanual.
FIGURE21.16 Selectinghelpfile
FIGURE21.17 Examplehelpmanual
21.4RunninganapplicationprogramVisualBasicallowsfortheexecutionofapplicationswiththeShellcommand.Itsformatis:
wherethewindowstyleisasdefinedinTable21.3.Ifthisargumentismissingthenthewindowstyleisthattheprogramisstartedwithaminimizedfocus.
Table21.3
Windowstylenamedargument
Constant Val Description
vbHide 0 Windowishiddenandfocusispassedtothehiddenwindow.
vbNormalFocus 1 Windowhasfocusandisrestoredtoitsoriginalsizeandposition.
vbMinimizedFocus 2 Windowisdisplayedasaniconwithfocus.
vbMaximizedFocus 3 Windowismaximizedwithfocus.
vbNormalNoFocus 4 Windowisrestoredtoitsmostrecentsizeandposition.Thecurrentlyactivewindowremainsactive.
vbMinimizedNoFocus 6 Windowisdisplayedasanicon.Thecurrentlyactivewindowremainsactive.
ThefollowingshowsanexampleofexecutingtheCalc.exeandNotepad.exeprograms:
21.5Exercises21.4.1.WriteaVisualBasicprogramwiththefollowingmenusystem:
21.4.2.ModifythemenusysteminExercise21.4.1sothattheprogramdisplaysthefunctionofthemenuoption.
21.4.3.ExpandProgram21.5anditsmenusystemsothatitrunsotherWindowsprograms.Anexamplecouldbe:
21.4.4.Integratesomeoftheprogramsfrompreviouschaptersintoasingleprogramwithmenuoptions.Forexample,themenusystemcouldbe:
Onepossiblemethodofimplementingthisprogramistocompilethetemperatureconversion,quadraticequationandstraightlineprogramstoanEXE(File→MakeEXEfile…).ThenruntheShellfunctionfromtheobjectcall.
22
Events
22.1Introduction
VisualBasicdiffersfrommanyotherprogramminglanguagesinthatitisevent-drivenwhere theexecutionofaprogram isdefinedby theevents thathappen.This is a different approach to many programming languages which follow adefinedsequenceofexecutionandtheprogrammermustdeveloproutineswhichreacttoevents.ThischapterdiscussestheeventsthathappeninVisualBasic.
22.2ProgrameventsEachobjectinVisualBasichasvariouseventsassociatedwithit.Forexample,the single click on an object may cause one event but a double click causesanother.Theeventsaredisplayedattheright-handsideofthecodewindow.AnexampleisshowninFigure22.1whichinthiscaseshowstheevents:KeyPress,KeyUp,LinkClose,LinkError,LinkExecute,LinkOpenandLoad.Thenameoftheroutinewhichcontainsthecodefortheeventandobjectisintheform:
FIGURE22.1 Formevents
ThemaineventsthatoccurinVisualBasicinclude:•Click.Whichoccurswhenauserperformsasingleclickofthemousebutton
ontheobject.•DblClick.Whichoccurswhenauserperformsadoubleclickofthemouse
buttonontheobject.•MouseUp.Whichoccurswhentheuserreleasesthemousebutton.•MouseDown.Whichoccurswhentheuserpressesthemousebuttondown.•MouseMove.Whichoccurswhentheusermovesthemouse.•KeyUp.Whichoccurswhentheuserreleasesakey.•KeyDown.Whichoccurswhentheuserpressesakey.•KeyPress.Whichoccurswhentheuserpressesandreleasesakey(the
KeyDownandKeyUpevents).•Load.Whichoccurswhenaformisloaded.•DragDrop.Whichoccursatthebeginandendofadragoperationofany
control.•LostFocus.Whichoccurswhenanobjectlosesthefocus,eitherbyuser
action,suchastabbingtoorclickinganotherobject.•Resize.Whichoccurswhenaformisfirstdisplayedoriftheobjectsizeis
changed.•Unload.Whichoccurswhenaformisabouttoberemovedfromthescreen.Notallcontrolsandforms(objects)havealltheeventsassociatedwiththem.
Forexampleaformmayhavethefollowing:
whereasacommandbuttonhasareducedsetofroutines:
Theparameterspassedintotheroutinedependontheactionsassociatedwiththe events. For example, theKeypress event on a commandbutton causes theroutine:
to be called. The value of KeyAscii will contain the ASCII value of thecharacterpress.The mouse down event for a command button has the following routine
associatedwithit:
wherethevalueofButtonisthevalueofthebuttonpress(0fornone,1fortheleft button and2 for the rightbutton).Shift specifies if the shift keyhasbeenpressed,andX,Yspecifythex,ycoordinatesofthemousepoint.Thefollowingsectionsdiscusssomeeventswhichoccur.
22.2.1ClickTheClickeventoccurswhentheuserpressesandthenreleasesamousebuttonoveranobject.Whentheobjectisaformtheeventoccurswhentheuserclicksonablankareaor adisabledcontrol. If theobject is a control, then theeventoccurswhentheuser:•Clicksonacontrolwithanyofthemousebuttons.Whenthecontrolisa
CheckBox,CommandButton,orOptionButtoncontrolthentheClickeventoccursonlywhentheuserclickstheleftmousebutton.
•PressestheALT-hotkeyforacontrol,suchaspressingAlt-XfortheE&xitcontrolpropertyname.
•PressestheEnterkeywhentheformhasacommandbutton.•PressestheSpacekeywhencommandbutton,optionbuttonorcheckbox
controlhasthefocus.
22.2.2DblClickTheDblClickeventoccurswhentheuserpressesandreleasesthemousebuttontwiceoveranobject.Inaformitoccurswhentheuserdoubleclickseitheronadisabledcontrolorablankareaofaform.Onacontroltheeventhappenswhentheuser:•Double-clicksonacontrolwiththeleftmousebutton.•Double-clicksanitemwithinaComboBoxcontrolwhoseStylepropertyisset
to1(Simple).AnexampleformisshowninFigure22.2.Inthiscaseatextboxisaddedto
theform.Thenthefollowingcodeisaddedtotheform:
FIGURE22.2 Formevents
whichwilldisplaythetext‘MISS’whentheuserclickonanyblankareaontheform.Thefollowingcodeisaddedtothetextbox:
whichdisplaysthetext‘HIT’whentheuserdoubleclicksonthetextbox.
22.2.3MouseUp,MouseDownTheMouseUp event occurs when the user releases themouse button and theMouseDowneventwhentheuserpressesamousebutton.Thestandardformatfortheassociatedroutinesare:
where•buttonidentifieswhichbuttonwaspressed(MouseDown)orreleased
(MouseUp).Thefirstbitofthevalueidentifiestheleftbutton,thesecondidentifiestherightbuttonandthethirdbitidentifiesthemiddlebutton.Thusavalueof1identifiestheleftbutton,avalueof2identifiestherightandavalueof4identifiesthemiddlebutton(ifthemousehasone).Acombinationofthesevaluescanbeusedtoidentifybuttonpresscombinations,suchasavalueof6identifiesthatthemiddleandrightbuttonshavebeenpressed.Table22.1showstheconstantnamesforthebuttons.
Table22.1Buttonconstants
Constant(Button) Value Description
vbLeftButton 1 Leftbuttonispressed
vbRightButton 2 Rightbuttonispressed
vbMiddleButton 4 Middlebuttonispressed
•shiftidentifiesthestateoftheShift,Cntrl,andAltkeyswhenthebuttonwaspressed(orreleased).ThefirstbitofthevalueidentifiestheShiftkey,thesecondbitidentifiestheCntrlkeyandthethirdbitidentifiestheAltkey.Thusavalueof1identifiestheShiftkey,avalueof2identifiestheCntrlkeyandavalueof4identifiestheAltkey.Acombinationofthesevaluescanbeusedtoidentifykeycombinations,suchasavalueof6identifiesthattheCntrlandAltkeysarepressed.Table22.1showstheconstantnamesforthekeys.
•x,yidentifiesthecurrentlocationofthemousepointer.ThexandyvaluesarerelativelytotheScaleHeight,ScaleWidth,ScaleLeft,andScaleToppropertiesoftheobject.
AnexampleofcodeforthemousedowneventisgivennextandasamplerunisshowninFigure22.3.
FIGURE22.3 Formevents
Table22.2Buttonconstants
Constant Value Description
vbShiftMask 1 SHIFTkeyispressed
vbCtrlMask 2 CTRLkeyispressed
vbAltMask 4 ALTkeyispressed
22.2.4MouseMoveThe MouseMove event occurs when the user moves the mouse. Thus it iscontinuallybeingcalledasitmovesacrossanobject.Thestandardformatfortheassociatedroutinesare:
wherebutton,shift,xandyhavethesamesettingsastheonesdefinedintheprevioussection.An example of code for theMouseMove event is given next and a sample
codeisshowninFigure22.4.Figure22.5showsasamplerun.Inthiscase,thexandycoordinateisthemousepointerandthebuttonpressedaredisplayedtothetextbox.
FIGURE22.4 Samplecode
FIGURE22.5 Samplerun
22.2.5DragAndDropThe DragDrop event occurs at the end of a drag and drop operation of anycontrol.Thestandardformatfortheassociatedroutinesare:
where:•sourceisthecontrolbeingdragged.•x,yspecifiesthecurrentxandycoordinateofthemousepointerwithinthe
targetformorcontrol.ThexandyvaluesarerelativetotheScaleHeight,ScaleWidth,ScaleLeft,andScaleToppropertiesoftheobject.
22.2.6KeypressThe KeyPress event occurs when the user presses and releases a key (theKeyDownandKeyUpevents).Thestandard format for theassociated routinesare:
whereKeyasciispecifiesastandardANSIkeycode,thiscanbeconvertedintoanASCIIcharacterwiththeconversionfunction:
AnexampleofcodefortheKeyPresseventisgivennextandasamplerunisshowninFigure22.6.Forthisprogramtheusercantypeintheblankareaontheform(thegreyarea)andthetextwillbedisplayedinthetextbox.
FIGURE22.6 Samplerun
22.2.7LostFocusTheLostfocusoccurswhenanobjectlosesthefocus,eitherbyuseraction,suchastabbingtoorclickinganotherobject.Thestandardformatfortheassociatedroutinesare:
22.2.8ResizeTheResize eventoccurswhena form is first displayedor if theobject size ischanged.Thestandardformatfortheassociatedroutinesare:
where:•heightisavaluespecifyingthenewheightofthecontrol.•widthisavaluespecifyingthenewwidthofthecontrol.
22.2.9UnloadTheUnloadeventoccurswhenaformisabouttoberemovedfromthescreen.Theniftheformisreloadedthecontentsofallitscontrolsarereinitialized.Thestandardformatfortheassociatedroutinesare:
wherecanceldetermineswhethertheformisremovedfromthescreen.Ifitis0thentheformisremovedelseitwillnotberemoved.
22.3Exercises22.3.1.WriteaVisualBasicprogramwhichhasasingleformandatextbox.
Thetextboxshouldshowalloftheeventsthatoccurwiththeform,thatis:
Investigatewhentheseeventsoccur.NoticethatwhenaneventhascodeattachedthentheprocedurenameintheViewCodepull-downmenubecomeshighlighted.
22.3.2.WriteaVisualBasicprogramwhichhasasinglecommandbuttonandatextbox.Thetextboxshouldshowalloftheeventsthatoccurwiththecommandbutton,thatis:
Investigatewhentheseeventsoccur.22.3.3.WriteaVisualBasicprograminwhichtheprogramdisplaysthemessage
‘INTEXTAREA’whenthemouseiswithinthetextboxareaand‘OUTOFTEXTAREA’whenitisoutofthetextboxarea.
22.3.4.WriteaVisualBasicprogramwhichhasacommandbutton.Iftheuserpressesanylowercaseletterthentheprogramends,elseitshouldcontinue.Asampleeventwhichquitswhentheletter‘x’ispressedisgivennext:
22.3.5.ModifytheprograminExercise22.3.4sothatiftheuserclicksontheform(andnotonthecommandbutton)theprogramautomaticallypromptstheuserforhis/hername.Thisnameshouldthenappearinthecommandbuttoncaptionproperty(Command1.caption).Anoutlineoftheeventisgivennext:
22.3.6.WriteaVisualBasicprogramwhichdisplaysthemessage‘Solongandthanksforthefish’whenthemainformisUnloaded.Theformshouldberemovedfromthescreen.
22.3.7.WriteaVisualBasicprogramwithatextboxwhichdisplaysthecurrentkeypress,includingAlt-,Ctrl-andShift-keystrokes.
22.3.8.ModifytheprograminExercise22.3.7sothatitalsodisplaysthemousebuttonpressandthecoordinatesofthemouse.
23
Graphics
23.1Introduction
Thischapterdiscusseshowgraphicsfilesareloadedintotheprogramandhowgraphicobjectscanbedrawn.
23.2LoadinggraphicsfilesVisualBasicallowsagraphicfile tobe loaded intoaform,apictureboxoranimagecontrol.Thestandardfunctionis:
Wheregraphfile specifies thenameof thegraphics file, ifnoname isgiventhen the graphic in the form, picture box or image control is cleared. ThestandardgraphicsfilessupportedbyVisualBasicare:•BMP.Windowsbitmapfile.•ICO.Iconfile(maximumsizeof32×32pixels).•RLE.Run-lengthencodedfiles.•WMF.Windowsmetafilefiles.
NormallygraphicsfilesaredisplayedinaPictureBox Thustodisplaythegraphicfile“CLOUD.BMP”toPicture1then:
Apicturecanbeloadedputintotheclipboardusing:
The following example loads a graphics file into a PictureBox. Figure 23.1shows a sample formwhich contains a PictureBox, a CommandButton and aDialogBox.
FIGURE23.1 Form
Thecodeaddedtothecommandbuttonisasfollows:
Thiswilldisplayadialogboxwiththedefaultfilesettingof*.BMP.AftertheuserhasselectedagraphicthentheLoadPicturefunctionisusedtodisplaythegraphicfiletothepicturebox(Picture1).Figure23.2showsasampledialogboxandFigure23.3showsasamplegraphic.
FIGURE23.2 Dialogbox
FIGURE23.3 Samplegraphic
Oneproblemwiththepreviousexamplecodeisthatanon-graphicfilecouldbeloadedandtheprogramwouldnotgiveanerrormessage.Thefollowingcodeovercomes this by testing for an error. This is achieved by testing the Errparameter after thepicturehasbeen loaded. If it is set toTRUE thenan errormessage isdisplayedand,after theuserhasaccepted theerror then thepicturewillbeclearedfromthepicturebox.
23.3ColoursThe background and foreground colour of an object can bemodifiedwith theBackColororForeColorproperty,respectively.Thestandardformis:
AcolourisdefinedasitsRGB(red/green/blue)strength,withahexadecimalstrength from&H00 to&H77 for each colour.The valid ranges of colour arethusfrom0to&HFFFFFF.
23.3.1RGBFunctionThe RGBColor function returns the hexadecimal colour value given the threestrengthsofred,greenandblue.Itsstandardformis:
wherered,greenandblueareavaluefrom0to255.Table23.1givessomeexamplecolourswiththeirRGBcolour.Forexample:
Table23.1Colourstrengths
23.3.2QBColorFunctionTheQBColorfunctionhasalimitedrangeof15,typicallycoloursasspecifiedinTable23.1.Forexample,thefollowingsetsthe
Table23.2Colourvalues
23.4DrawingVisualBasic has awide rangeof drawing functions (graphicsmethods); theseinclude:•Line.Drawslinesandrectanglesonanobject.
•Circle.Drawsacircle,ellipse,orarconanobject.•Cls.ClearsgraphicsandtextfromaFormorPictureBox.•Fillcolour.Returnsorsetsthecolourusedtofillinshapes(drawnbyLine
andCirclegraphicsmethods).•Fillstyle.ReturnsorsetsthepatternusedtofillShapes(ascreatedbyLineor
Circlegraphicsmethods).
23.4.1LineTheLinegraphicmethoddraws linesand rectanglesonanobject. Its standardformis:
where:•Step.Keywordspecifyingthestartingpointco-ordinates.(Optional)•(x1,y1)
Definethestartingpointco-ordinatesofalineorrectangle.Iftheyareomittedthenthelinestartsatthecurrentx,yposition(CurrentXandCurrentY).Optional•Step.Keywordspecifyingtheendpointco-ordinates.(Optional)•(x2,y2)Definetheendpointco-ordinatesofalineorrectangle.(Required)•color.DefinestheRGBcolourusedtodrawtheline.IfitisomittedthentheForeColorpropertysettingisused.(Optional)•B.IftheBoptionisaddedthenaboxisdrawnusingtheco-ordinatesforoppositecorners.(Optional)•F.IftheFoptionisaddedthentheboxisfilledwiththesamecolourasthelinecolour.(Optional)
TheCurrentXandCurrentYvaluesareset to theendof the lineaftera linehas been drawn. The DrawWidth property sets the width of the line andDrawMode and DrawStyle properties define the way that the line or box isdrawn.ThefollowingcodeisaddedtoaformandwiththeClickevent.Itdisplays15
solidrectanglesofarandomsizeandrandomcolour.TheQBColorfunctionisused to display one of the 16 predefined colours. Note that the Rnd functionreturnsarandomnumberfrom0to1.
FIGURE23.4 Samplegraphic
23.4.2CircleThe Circle graphic method draws a circle, ellipse or an arc on an object. Itsstandardformis:
where:•Step.Keywordspecifyingthatthecentreofthecircle,ellipse,orarcis
relativetothecurrentco-ordinatesgivenbytheCurrentXandCurrentYpropertiesofobject.(Optional)•(x,y).Valuewhichgivestheco-ordinatesofthecentreofthecircle,ellipseorarc.(Required)•radius.
Valuewhichspecifiestheradiusofthecircle,ellipseorarc.(Required)•color.Valuewhichspecifiesthecolourofthecircle’soutline.Ifomitted,thevalueoftheForeColorpropertyisused.(Optional)•start,end.Valuesspecifyingthestartandendangle(inradians)foranarcorapartialcircleorellipseisdrawn,startandendspecify(inradians)thebeginningandendpositionsofthearc.(Optional)•aspect.Valuespecifyingtheaspectratioofthecircle.Thedefaultvalueis1.0,whichyieldsaperfectcircle.(Optional)
TheQBColororRGBfunctionaretypicallyusedtosetthecolour.AcircleisfillwithadefinedcolourwiththeFillColorpropertyandthefillstyleissetbytheFillStyleproperties.TheDrawWidthpropertydefines thewidthof the lineusedtodrawthecircle,ellipse,orarc.Thefollowingexamplecodedraws10circlesofincreasingsizeofarandom
colour.Figure23.5showsasamplerun.
FIGURE23.5 Samplegraphic
23.4.3DrawWidthTheDrawWidthpropertyreturnsorsetsthelinewidthofagraphicmethod.Tosetthewidthoflinethefollowingisused:
where the size is a value from1 (the default) to 32,767 and ismeasured inpixels.
23.4.4DrawStyleTheDrawWidthpropertyreturnsorsetsthelinestyleofagraphicmethod.Tosetthelinestylethefollowingisused:
wherevalue is anumber from0 (thedefault) to6whichcorresponds to thefollowinglinestyles:
ForexampletosetalinestyleonaFormtodashed:
DrawWidth=l
23.4.5FillColorTheFillColor property returns or sets the colour used to fill in shapes, circlesandboxes.Tosetthefillcolourthefollowingisused:
wherethesizeisahexadecimalcolourandbydefaultitisBlack.
23.4.6FillStyleTheFillStylepropertyreturnsorsetsthefillstyleofagraphicmethod.Tosetthelinestylethefollowingisused:
wherevalue is anumber from0 (thedefault) to6whichcorresponds to thefollowinglinestyles:
The following example displays 15 randomly filled circleswith a radius of200pixels.It is initiatedwiththeuserclicksontheform.Figure23.6showsasamplerun.
FIGURE23.6 Samplegraphic
23.4.7CurrentX,CurrentYTheCurrentXandCurrentYproperty returnor sets the horizontal andvertical(CurrentY)co-ordinates,respectively.Thestandardformatis:
The(0,0)co-ordinateisattheupper-lefthandcornerofanobject.
23.4.8CIs
TheClsmethodclearsgraphicsand textgeneratedat run timefromaFormorPictureBox.Itsstandardformis:
23.5Exercises23.5.1.Writeaprogramwhichdisplaysacolouredrectangleinthemiddleofa
form.Eachtimetheuserclicksontheformtherectangleshouldchangecolour.
23.5.2.WriteaVisualBasicprogramwhichautomaticallymovesarectanglefromthetopleft-handsideofthescreentothebottomright-handside.Theprogramshouldquitonceitreachesthebottomcorner.
23.5.3.WriteaVisualBasicprogramwhichrandomlymovesasmallrectanglearoundthescreen.Iftherectangletouchesanyoftheedgesitshouldreboundofftheedge.
23.5.4.WriteaVisualBasicprograminwhichtheusercontrolsthemovementofasmallrectanglebythearrowkeys.
23.5.5.WriteaVisualBasicprogramwhichdisplaysacircleontheformwhichfollowstheusersmousecursor(noteusetheclsfunctiontogetridoftheexistingcircle).
23.5.6.WriteseparateVisualBasicprogramswhichdrawthefollowingobjects:(i)Acar.
(ii)Aship.(iii)Ahouse.
23.5.7.WriteaVisualBasicprogramwhichdisplaysthefollowingimages.Usethesleepandclsfunctionstocreateatimingdelayof1secondbetweeneachimagedisplay(theanimationshouldlookasifitiswinking).
24
HTML(Introduction)
24.1Introduction
HTMLisastandardhypertextlanguagefortheWWWandhasseveraldifferentversions.MostWWWbrowserssupportHTML2andmostofthenewversionsof the browsers supportHTML3.WWWpages are created and editedwith atext editor, a word processor or, as is becoming more common, within theWWWbrowser.HTMLtagscontainspecialformattingcommandsandarecontainedwithina
less than (<) and a greater than (>) symbol (which are also known as angledbrackets). Most tags have an opening and closing version; for example, tohighlight bold text the bold opening tag is <B>and the closing tag is</B> .Table24.1outlinesafewexamples.
Table24.1ExampleHTMLtags
Opentag Closingtag Description
<HTML> </HTML> StartandendofHTML
<HEAD> </HEAD> DefinestheHTMLheader
<BODY> </BODY> DefinesthemainbodyoftheHTML
<TITLE> </TITLE> DefinesthetitleoftheWWWpage
<I> </I> Italictext
<B> </B> Boldtext
<U> </U> Underlinedtext
<BLINK> </BLINK> Maketextblink
<EM> </EM> Emphasizetext
<FONTSIZE=+1> </FONT> Increasefontsizebyoneincrement
<FONTSIZE=–1> </FONT> Reducefontsizebyoneincrement
Centertext
<CENTER> </CENTER>Centertext
<H1> </H1> Sectionheader,level1
<H2> </H2> Sectionheader,level2
<H3> </H3> Sectionheader,level3
<P> Createanewparagraph
<BR> Createalinebreak
<excl––> ––> Comments
<SUPER> </SUPER> Superscript
<SUB> </SUB> Subscript
HTMLscript1givesanexamplescriptandFigure24.1showstheoutputfromtheWWWbrowser.Thefirstlineisalways<HTML>andthelastlineis</HTML>.After this line theHTMLheader isdefinedbetween<HEAD>and</HEAD>.ThetitleofthewindowinthiscaseisMyfirstHTMLpage.ThemainHTMLtextisthendefinedbetween<BODY>and</BODY>.
FIGURE24.1 ExamplewindowfromexampleHTMLscript
TheWWWbrowserfitstextintothewindowsizeanddoesnotinterpretlinebreaksintheHTMLsource.Toforceanewlinethe<BR>(linebreak)oranewparagraph (<p>) is used. The example also shows bold, italic and underlinedtext.
24.2LinksThe topology of the WWW is set-up using links where pages link to otherrelatedpages.Areferencetakestheform:
whereurl defines theURL for the file,ReferenceName is the name of thereference and </A> defines the end of the reference name. HTML script 24.2shows an example of the uses of references and Figure 24.2 shows a samplebrowser page. The background colour is set using the <BODY BGCOLOR= “#
FFFFFF”>whichsetthebackgroundcolourtowhite.Inthiscasethedefaulttextcolourisblackandthelinkiscolouredblue.
FIGURE24.2 ExamplewindowfromexampleHTMLscript24.2
24.2.1OtherLinksLinkscanbeset-uptosende-mailandnewsgroups.Forexample:
tolinktoatennisnewsgroupand
tosendamailmessagetothee-mailaddress:[email protected].
24.3ListsHTMLallowsorderedandunorderedlists.ListscanbedeclaredanywhereinthebodyoftheHTML.
24.3.1OrderedListsThestartofanorderedlistisdefinedwith<OL>andtheendofthelistby</OL>.Eachpart of the list is defined after the<LI> tag.Unordered lists are definedbetween the <UL> and </UL> tags. HTML script 24.3 gives examples of anorderedandanunorderedlist.Figure24.3showstheoutputfromthebrowser.
FIGURE24.3 WWWbrowserwithanorderedandunorderedlists
Some browsers allow the type of numbered list to be definedwith the <OLTYPE=x>,wherexcaneitherbe:•Aforcapitalletters(suchasa,b,c,andsoon).•aforsmallletters(suchasa,b,c,andsoon).•Iforcapitalromanletters(suchasI,II,III,andsoon).•iforsmallromanletters(suchasi,ii,iii,andsoon).•Ifornumbers(whichisthedefault).
wouldbedisplayedas:IList1
IIList2IIIList3
AList1BList2CList3
Thestartingnumberofthelistcanbedefinedusingthe<LIVALUE=n>wherendefinestheinitialvalueofthedefineditemlist.
24.3.2UnorderedListsUnorderedlistsareusedtolistaseriesofitemsinnoparticularorder.Theyaredefined between the <UL> and </UL> tags. Some browsers allow the type ofbulletpointtobedefinedwiththe<LITYPE=shape>,whereshapecaneitherbe:•discforroundsolidbullets(whichisthedefaultforfirstlevellists).•roundforroundhollowbullets(whichisthedefaultforsecondlevellists).•squareforsquarebullets(whichisthedefaultforthird).HTMLscript 24.4gives an exampleof anunnumbered list andFigure24.4
shows theWWWpageoutput for this script. It canbe seen from this that thedefaultbulletsforlevel1listsarediscs,forlevel2theyareroundandforlevel3theyaresquare.
FIGURE24.4 WWWpagewithanunnumberedlist
24.3.3DefinitionListsHTMLusesthe<DL>and</DL>tagsfordefinitionlists.Thesearenormallyusedwhenbuildingglossaries.Eachentryinthedefinitionisdefinedbythe<DT>tagandthetextassociatedwiththeitemisdefinedafterthe<DD>tag.Theendofthelist isdefinedby</DL>.HTMLscript24.5showsanexamplewithadefinitionlist andFigure 24.5 gives a sample output.Note that it uses the<EM> tag toemphasizethedefinitionsubject.
FIGURE24.5 WWWpagewithdefinitionlist
24.4ColoursColoursinHTMLaredefinedintheRGB(red/green/blue)strength.Theformatis#rrggbb,whererr is thehexadecimal equivalent for the redcomponent,ggthe hexadecimal equivalent for the green component and bb the hexadecimalequivalentforthebluecomponent.Table24.2listssomeofthecodesforcertaincolours.
Table24.2Hexadecimalcolours
Individual hexadecimal numbers use base 16 and range from 0 to F (indecimalthisrangesfrom0to15).Atwo-digithexadecimalnumberrangesfrom00toFF(indecimalthisrangesfrom0to255).Table24.3outlineshexadecimalequivalents.
Table24.3Hexadecimaltodecimalconversions
HTMLusespercentagestrengthsfor thecolours.Forexample,FF representsfull strength (100%) and 00 represent no strength (0%). Thus, white is madefromFF (red),FF (green) andFF (blue) andblack ismade from00 (red),00(green)and00(blue).Greyismadefromequalweightingofeachofthecolours,suchas43,43,43fordarkgrey(#434343)andD4,D4andD4forlightgrey(#D4D4D4).Thus,pureredwithbe#FF0000,puregreenwillbe#00FF00andpurebluewithbe#0000FF.Eachcolourisrepresentedby8bits,thusthecolourisdefinedby24bits.This
givesa totalof16777216colours (224differentcolours).Note thatsomevideodisplayswillnothaveenoughmemorytodisplay16.777millioncoloursinthecertainmode so that coloursmaydifferdependingon theWWWbrowser andthegraphicsadapter.The colours of the background, text and the link can be defined with the
BODY tag. An example with a background colour of white, a text colour oforangeandalinkcolourofdarkredis:
andforabackgroundcolourofred,atextcolourofgreenandalinkcolourofblue:
When a link has been visited its colour changes. This colour itself can bechangedwiththeVLINK.Forexample,toset-upavisitedlinkcolourofyellow:
Notethatthedefaultlinkcoloursare:
24.5BackgroundimagesImage(suchasGIFandJPEG)canbeusedasabackgroundtoaWWWpage.For this purpose the option BACKGROUND=‘src.gif’ is added to the <BODY>tag.AnHTML scriptwith a background ofCLOUDS.GIF is given inHTMLscript24.6.AsampleoutputfromabrowserisshowninFigure24.6.
FIGURE24.6 WWWpagewithCLOUD.GIFasabackground
24.6DisplayingimagesWWW pages can support graphics images within a page. The most commonsources of images are either JPEG or GIF files, as these types of imagesnormally have a high degree of compression. GIF images, as was previouslymentioned, support only 256 colours from a pallet of 16.7 million colours,whereasJPEGsupportsmorethan256colours.
24.6.1InsertingAnImageImages can be displayed within a page with the <‘IMG SRC=‘src.gif’> whichinserts thegraphicsrc.gif.HTMLscript24.7contains three images:myson.gif,me.gifandmyson2.gif.ThesearealignedeithertotheleftortherightusingtheALIGNoptionwithinthe<IMGSRC>tag.Thefirstimage(myson.gif)isalignedtotheright,whilethesecondimage(me.gif)isalignedtotheleft.Figure24.7shows a sample output from this script. Note that images are left aligned bydefault.
FIGURE24.7 WWWpagewiththreeimages
24.6.2AlternativeTextOften users choose not to view images in a page and select an option on theviewerwhichstopstheviewerfromdisplayinganygraphicimages.IfthisisthecasethentheHTMLpagecancontainsubstitutetextwhichisshowninsteadoftheimage.Forexample:
24.6.3OtherOptionsOtherimageoptionscanbeadded,suchas:•HSPACE=xVSPACE=ydefinestheamountofspacethatshouldbeleftaround
images.Thexvaluedefinesthenumberofpixelsinthex-directionandtheyvaluedefinesthenumberofpixelsinthey-direction.
•WIDTH=xHEIGHT=ydefinesthescalinginthex-andy-direction,wherexandyarethedesiredpixelwidthandheight,respectively,oftheimage.
•ALIGN=directiondefinesthealignmentoftheimage.Thiscanbeusedtoalignanimagewithtext.Validoptionsforaligningwithtextaretexttop,top,middle,absmiddle,bottom,baselineorabsbottom.HTMLscript24.8showsanexampleofimagealignmentwiththeimagea.gif(whichisjust
theletter‘A’asagraphic)andFigure24.8showsasampleoutput.Itcanbeseenthattexttopalignstheimagewithhighestpartofthetextontheline,topalightstheimagewiththehighestelementintheline,middlealignswiththemiddleoftheimagewiththebaseline,absmiddlealightsthemiddleoftheimagewiththemiddleofthelargestitem,bottomalignsthebottomoftheimagewiththebottomofthetextandabsbottomalignsthebottomoftheimagewiththebottomofthelargestitem.
FIGURE24.8 WWWpageshowingimagealignment
24.7HorizontallinesAhorizontal line can be addedwith the <HR> tag.Most browsers allow extraparameters,suchas:SIZE=n–whichdefinesthattheheightoftheruleisnpixels.WIDTH=w–whichdefinesthatthewidthoftheruleiswpixelsorasapercentage.
ALIGN=direction–wheredirectionreferstothealignmentoftheruleValidoptionsfordirectionareleft,rightorcenter.
NOSHADE–whichdefinesthatthelineshouldbesolidwithnoshading.HTMLscript24.9givessomeexamplehorizontallinesandFigure24.9shows
anexampleoutput.
FIGURE24.9 WWWpageshowinghorizontallines
24.8Exercises24.8.1.ThehomepageforthisbookcanbefoundattheURL:
Accessthispageandfollowanylinksitcontains.24.8.2.Ifpossible,createaWWWpagewiththefollowingblinkingtext:
24.8.3.Thelastpartoftheservernamenormallygivesanindicationofthecountrywheretheserverislocated(forexamplewww.fredco.co.ukislocatedintheUK).Determinewhichcountriesusethefollowingcountrynames:(a)de(b)nl(c)it(d)se(e)dk(f)sg(g)ca(h)ch(i)tr(j)jp(k)au
Determinesomeothercountryidentifiernames.24.8.4.DeterminetheHTMLcolourrepresentforthefollowing:
(a)red(b)green(c)blue(d)white(e)black
24.8.5.DeterminetheHTMLforthebackground,textandlinkcolour:
25
FurtherHTML
25.1Introduction
Chapter 24 introduced HTML; this chapter discusses some of HTML’s moreadvanced features. HTML differs from compiled languages, such as C andPascal,inthattheHTMLtextfileisinterpretedbyaninterpreter(thebrowser)while languagessuchasCandPascalmustbeprecompiledbefore theycanberun.HTMLthushas theadvantage that itdoesnotmatter if it is theoperatingsystem,thebrowsertypeorthecomputertypethatreadstheHTMLfile,asthefile does not contain any computer specific code. The main disadvantage ofinterpretedfilesisthattheinterpreterdoeslesserrorcheckingasitmustproducefastresults.ThebasicpagesontheWWWarelikelytoevolvearoundHTMLandwhile
HTML can be produced manually with a text editor, it is likely that, in thecomingyears,therewillbeanincreaseintheamountofgraphically-basedtoolsthatwillautomaticallyproduceHTMLfiles.Althoughthesetoolsaregraphics-basedtheystillproducestandardHTMLtextfiles.ThusaknowledgeofHTMLis important as itdefines thebasic specification for thepresentationofWWWpages.
25.2AnchorsAnanchor allowsusers to jump froma reference in aWWWpage to anotheranchorpointwithinthepage.Thestandardformatis:
whereanchornameisthenameofthesectionwhichisreferenced.The</A>tagdefinestheendofananchorname.Alinkisspecifiedby:
followedbythe</A>tag.HTMLscript25.1showsasamplescriptwithfouranchorsandFigure25.1showsasampleoutput.Whentheuserselectsoneofthereferences, thebrowser automatically jumps to that anchor.Figure25.2 showsthe output screen when the user selects the #Token reference. Anchors aretypicallyusedwhenanHTMLpage is longorwhenabackwardsor forwardsreferenceoccurs(suchasareferencewithinapublishedpaper).
FIGURE25.1 Examplewindowwithreferences
FIGURE25.2 Examplewindowwithreferences
25.3TablesTablesareoneof thebestmethodstodisplaycomplexinformationinasimpleway.Unfortunately,inHTMLtheyarerelativelycomplicatedtosetup.Thestartofatableisdefinedwiththe<TABLE>tagandtheendofatableby</TABLE>.Arow is defined between the <TR> and </TR>, while a table header is definedbetween <TH> and </TH>. A regular table entry is defined between <TD> and</TD>.HTMLscript25.2showsanexampleofatablewithlinkstootherHTMLpages.TheBORDER=noptionhasbeenaddedtothe<TABLE>tagtodefinethethickness of the table border (in pixels). In this case the border size has athicknessof10pixels.
FIGURE25.3 ExamplewindowfromexampleJavascript
Otheroptionsinthe<TABLE>tagare:•WIDTH=x,HEIGHT=y–definesthesizeofthetablewithrespecttothefull
windowsize.Theparametersxandyareeitherabsolutevaluesinpixelsfortheheightandwidthofthetableorarepercentagesofthefullwindowsize.
•CELLSPACING=n–definesthenumberofpixelsdesiredbetweeneachcellwherenisthenumberofpixels(notethatthedefaultcellspacingis2
pixels).Anindividualcellcanbemodifiedbyaddingoptionstothe<TH>or<TD>tag.
Theseinclude:•WIDTH=x,HEIGHT=y–definesthesizeofthetablewithrespecttothetable
size.Theparametersxandyareeitherabsolutevaluesinpixelsfortheheightandwidthofthetableorarepercentagesofthetablesize.
•COLSPAN=n–definesthenumberofcolumnsthecellshouldspan.•ROWSPAN=n–definesthenumberofrowsthecellshouldspan.•ALIGN=direction–defineshowthecell’scontentsarealignedhorizontally.
Validoptionsareleft,centerorright.•VALIGN=direction–defineshowthecell’scontentsarealignedvertically.
Validoptionsaretop,middleorbaseline.•NOWRAP–informsthebrowsertokeepthetextonasingleline(thatis,withno
linebreaks).HTML script 25.3 shows an example use of some of the options in the
<TABLE> and <TD> options. In this case the text within each row is centrealigned. On the second row the second and third cells are merged using theCOLSPAN=2 option. The first cell of the second and third rows have also beenmergedusingtheROWSPAN=2option.Figure25.4showsanexampleoutput.Thetablewidthhasbeenincreasedto90%ofthefullwindow,withawidthof50%.
FIGURE25.4 Examplewindowfromexamplescript
25.4CGIscriptsCGI (CommonGateway Interface) scripts are normallywritten in either C orPerl andare compiled toproduce an executableprogram.Theycanalso comeprecompiledorintheformofabatchfile.Perlhastheadvantageinthatitisascript thatcanbeeasily runonanycomputer,whileaprecompiledCprogramrequirestobeprecompiledfortheservercomputer.CGI scripts allow the user to interactwith the server and store and request
data. They are often used in conjunction with forms and allow an HTMLdocumenttoanalyze,parseandstoreinformationreceivedfromaform.OnmostUNIX-typesystemsthedefaultdirectoryforCGIscriptsiscgi-bin.
25.5FormsFormsareexcellentmethodsofgatheringdataandcanbeused inconjunctionwithCGIscriptstocollectdataforfutureuse.Aformisidentifiedbetweenthe<FORM>and</FORM>tags.Themethodused
to get the data from the form is defined with the METHOD= “POST”. The
ACTIONoptiondefines theURLscript tobe runwhen the form issubmitted.Datainputisspecifiedbythe<INPUTTYPE>tag.HTMLscript25.4formhasthefollowingparts:•<formaction="cgi-binAnyForm2”method="POST">–whichdefinesthe
startofaformandwhenthe“submit”optionisselectedthecgiscriptcgi-binAnyForm2willbeautomaticallyrun.
•<inputtype="submit”value="SendFeedback">-whichcausestheprogramdefinedintheactionoptioninthe<form>tagtoberun.Thebuttonontheformwillcontainthetext“SendFeedback”,seeFigure25.5forasampleoutputscreen.
FIGURE25.5 Examplewindowshowinganexampleform
•<inputtype=“reset”value=“ResetForm”>–whichresetsthedataintheform.Thebuttonontheformwillcontainthetext“ResetForm”,seeFigure25.5forasampleoutputscreen.
•<inputtype="hidden”name="AnyFormTo”value=“[email protected]">–whichpassesavalueoff.bloggs@toytown.ac.ukwhichhastheparameternameof“AnyFormTo”.TheprogramAnyForm2takesthisparameterandautomaticallysendsittotheemailaddressdefinedinthevalue(thatis,[email protected]).
•<inputtype="hidden”name="AnyFormSubject”value="Feedbackform">–
whichpassesavalueofFeedbackformwhichhastheparameternameof“AnyFormSubject”.TheprogramAnyForm2takesthisparameterandaddsthetext“Feedbackform”inthetextsenttotheemailrecipient(inthiscase,[email protected]).
•Surname<inputname="Surname">–whichdefinesatextinputandassignsthisinputtotheparameternameSurname.
•<textareaname="Address”rows=2cols=40></textarea>–whichdefinesatextinputareawhichhastworowsandhasawidthof40characters.Thethumbbarsappearattheright-handsideoftheformifthetextareaexceedsmorethan2rows,seeFigure25.5.
Inthiscasetherecipient([email protected])willreceiveanemailwiththecontents:
Theextraoptionstothe<input>tagaresize=”n“,wherenisthewidthoftheinputboxincharacters,andmaxlength=”m“,wheremisthemaximumnumberofcharactersthatcanbeentered,incharacters.Forexample:
definesthattheinputtypeistext,thewidthoftheboxis15charactersandthemaximumlengthofinputis10characters.
25.5.1InputTypesThe type options to the <input> tag are defined in Table 25.1.HTML script25.5givesafewexamplesofinputtypesandFigure25.6showsasampleoutput.
Table25.1Inputtypeoptions
FIGURE25.6 Examplewindowwithdifferentinputoptions
25.5.2MenusMenus are a convenient method of selecting from multiple options. The<SELECT> tag is used to define start of a list of menu options and the</SELECT> tag defines the end. Menu elements are then defined with the<OPTION>tag.Theoptionsdefinedwithinthe<SELECT>are:•NAME=”name“–whichdefinesthatnameisthevariablenameofthemenu.
Thisisusedwhenthedataiscollectedbytheserver.•SIZE=“n”–whichdefinesthenumberofoptionswhicharedisplayedinthe
menu.HTMLscript25.6showsanexampleofamenu.Theadditionaloptionstothe
<OPTION>tagare:•SELECTED–whichdefinesthedefaultselectedoption.•VALUE=”val“–wherevaldefinesthenameofthedatawhenitiscollectedby
theserver.
FIGURE25.7 Examplewindowshowinganexampleform
25.6MultimediaIf thebrowser cannothandle all the file types itmaycall onother applicationhelperstoprocessthefile.Thisallowsother‘third-party’programstointegrateinto the browser. Figure 25.8 shows an example of the configuration of thehelperprograms.Theoptionsinthiscaseare:
FIGURE25.8 Examplewindowshowinganexampleform
•Viewinbrowser.•Savetodisk.•Unknown:promptuser.•Launchanapplication(suchasanaudioplaybackprogramorMPEGviewer).For certain applications the user can select as to whether the browser
processesthefileoranotherapplicationprogramprocessesit.Helperprogramsmakeupgrades inhelperapplications relativelysimpleandalsoallownewfiletypes to be added with an application helper. Typically when a program isinstalled which can be used with a browser it will prompt the user toautomatically update the helper application list so that it can handle the givenfiletype(s).Eachfiletypeisdefinedbythefileextension,suchas.psforpostscriptfiles,
.exe for a binary executable file, and so on. These file extensions have beenstandardized in MIME (Multipurpose Internet Mail Extensions) specification.Table25.2showssometypicalfileextensions.
Table25.2Inputtypeoptions
Mimetype Extension Typicalaction
application/octet-stream exe,bin Save
application/postscript ps,ai,eps Askuser
application/x-compress Z Compressprogram
application/x-gzip gz GZIPcompressprogram
application/x-javascript js,mocha Askuser
application/x-msvideo avi Audioplayer
application/x-perl P1 Save
application/x-tar tar Save
application/x-zip-compressed zip ZIPprogram
audio/basic au,snd Audioplayer
image/gif gif Browser
image/jpeg jpeg,jpg,jpe Browser
image/tiff tif,tiff Graphicsviewer
image/x-MS-bmp bmp Graphicsviewer
text/html htm,html Browser
text/plain text,txt Browser
video/mpeg mpeg,mpg,mpe,mpv,vbs,mpegv Videoplayer
video/quicktime qt,mov,moov Videoplayer
25.7Exercises25.7.1.ConstructaWWWpagewithanchorpointsforthefollowing:Selectthenetworkyouwishtofindoutabout:EthernetTokenringFDDI
EthernetEthernet is themost widely used networking technology used in LAN (LocalAreaNetwork).Initselfitcannotmakeanetworkandneedssomeotherprotocolsuch as TCP/IP or SPX/IPX to allow nodes to communicate. Unfortunately,Ethernetinitsstandardformdoesnotcopewellwithheavytraffic.Itshasmanyadvantages,though,including:•Networksareeasytoplanandcheaptoinstall.•Networkcomponentsarecheapandwellsupported.•Itiswell-proventechnologywhichisfairlyrobustandreliable.•Simpletoaddanddeletecomputersonthenetwork.•Supportedbymostsoftwareandhardwaresystems.
TokenringToken ring networks were developed by several manufacturers, the mostprevalentbeingtheIBMTokenRing.Tokenringnetworkscopewellwithhighnetwork traffic loadings. They were at one time extremely popular but theirpopularityhassincebeenovertakenbyEthernet.Tokenringnetworkshave, inthepast, suffered fromnetworkmanagementproblemsandpoornetwork faulttolerance.Tokenringnetworksarewellsuitedtosituationswhichhavelargeamountsof
trafficandalsoworkwellwithmosttrafficloadings.Theyarenotsuitedtolargenetworksornetworkswithphysicallyremotestations.Theirmainadvantage isthattheycopebetterwithhightrafficratesthanEthernet,butrequireagreatdealofmaintenanceespeciallywhenfaultsoccurorwhennewequipmentisaddedtoorremovedfromthenetwork.ManyoftheseproblemshavenowbeenovercomebyMAUs (multi-station access units), which are similar to the hubs using inEthernet.
FDDIA token-passing mechanism allows orderly access to a network. Apart fromtoken ring the most commonly used token-passing network is the FiberDistributedDataInterchange(FDDI)standard.Thisoperatesat100Mbpsand,toovercometheproblemsof linebreaks,hastwoconcentric tokenrings.Fibreoptic cables have a much high specification over copper cables and allowextremelylonginterconnectionlengths.Themaximumcircumferenceoftheringis100km(62miles),withamaximum2kmbetweenstations(inFDDIstationsare also known as stations). It is thus an excellentmechanism for connectinginterconnectingnetworksoveracityoracampus.Upto500stationscanconnecttoeachringwithamaximumof1,000stationsforthecompletenetwork.EachstationconnectedtotheFDDIhighwaycanbeanormalstationorabridgetoaconventionallocalareanetwork,suchasEthernetortokenring.25.7.2.ConstructaWWWglossarypagewiththefollowingterms:
Address Auniquelabelforthelocationofdataortheidentityofacommunicationsdevice.
AddressResolutionProtocol(ARP)
ATCP/IPprocesswhichmapsanIPaddresstoanEthernetaddress.
AmericanNationalStandardsInstitute(ANSI)
ANSIisanon-profitorganizationwhichismadeupofexpertcommitteesthatpublishstandardsfornationalindustries.
AmericanStandard AnANSI-definedcharacteralphabetwhichhassincebeenadoptedasastandardinternationalalphabetfortheinterchangeofcharacters.
CodeforInformationInterchange(ASCII)
internationalalphabetfortheinterchangeofcharacters.
Amplitudemodulation(AM)
Informationiscontainedintheamplitudeofacarrier.
Amplitude-ShiftKeying(ASK)
Usestwo,ormore,amplitudestorepresentbinarydigits.Typicallyusedtotransmitbinarydataoverspeech-limitedchannels.
Applicationlayer ThehighestlayeroftheOSImodel.
Asynchronoustrans-mission
Transmissionwhereindividualcharactersaresentone-by-one.Normallyeachcharacterisdelimitedbyastartandstopbit.Withasynchronouscommunicationthetransmitterandreceiveronlyhavetoberoughlysynchronized.
25.7.3.ConstructaWWWpagewhichcanbeusedtoenteraperson’sCV(note,useaform).Thebasicfieldsshouldbe:
Name:Address:Emailaddress:Telephonenumber:Experience:Interests:Anyotherinformation:
25.7.4.WriteanHTMLscriptwhichdisplaysthefollowingtimetable.
25.7.5.Designyourownhomepagewithabasicuserhomepage(index.html)whichcontainslinkstoabasicCVpage(forexample,itcouldbenamedcv.html)andapagewhichlistsyourmaininterests(myinter.html).Designoneofthehomepageswithalistoflinksandanotherwithatableoflinks.Ifpossibleincorporategraphicsfilesintothepages.
26
JavaScript
26.1Introduction
Computersystemscontainamicroprocessorwhichcontrolstheoperationofthecomputer.Themicroprocessoronlyunderstandsbinaryinformationandoperatesonaseriesofbinarycommandsknownasmachinecode.Itisextremelydifficulttowrite largeprogramsinmachinecode,so thathigh-level languagesareusedinstead. A low-level language is one which is similar to machine code andnormally involves the usage of keyword macros to replace machine codeinstructions. High-level languages have a syntax that is almost like writtenEnglishandthusmakeprogramseasytoreadandtomodify.Inmostprogramstheactualoperationofthehardwareisinvisibletotheprogrammer.Acompilerchanges the high-level language into machine code. Typical high-levellanguagesincludeC/C++,BASIC,COBOL,FORTRANandPascal;anexampleofalow-levellanguageis80486AssemblyLanguage.Java is a high-level language that has been developed specifically for the
WWWandiswellsuitedtonetworkedapplications.ItwasoriginallydevelopedbySunMicrosystemsand isbasedonC++ (butwith lessof thedifficultiesofC++).MostnewversionsofWebbrowsersnowsupport itsusage.Java’smainattributesare:•Itrunseitherasastand-aloneprogramoritcanrunwithintheWebbrowser.
WhenrunwithinthebrowsertheJavaprogramisknownasanapplet.•Javaisaportablelanguageandappletscanrunonanytypeofmicroprocessor
type(suchasaPCbasedonIntel80486orPentium,oraMotorola-basedcomputer).
•Javaappletsarehardwareandoperatingsystemindependent.Forexample,theprogramitselfdoesnothavetointerfacedirectlytothehardwaresuchasavideoadapterormouse.Typicalhigh-levellanguages,suchasC/C++andPascal,producemachine-dependentmachinecode,andcanthusonlybeexecutedonaspecificcomputeroroperatingsystems.
•Javaallowsforaclient/serverapproachwheretheappletcanrunontheremotecomputerwhichthusreducestheloadingonthelocalcomputer(typicallytheremotecomputerwillbeapowerfulmultitaskingcomputerwithenhancedcomputerarchitecture).
•AJavacompilercreatesstand-aloneprogramsorapplets.ManynewversionsofbrowsershaveanintegratedJavacompiler.
Figure 26.1 shows the main functional differences between a high-levellanguage, a Java applet and JavaScript. JavaScript is interpret by the browser,whereasaJavaappletiscompiledtoavirtualmachinecodewhichcanberunonanycomputersystem.Thehigh-levellanguageproducesmachine-specificcode.
FIGURE26.1 DifferencesbetweenC++/JavaandJavaScript
AnormalC++ program allows access to hard-disk drives. Thiswould be aproblemontheWebasunsolicitedusers(‘hackers’)ornoviceuserscouldcausedamageontheWebserver.ToovercomethisJavadoesnothaveanymechanismforfileinput/output(I/O).Itcanreadstandardfiletypes(suchasGIFandJPG)butcannotstorechangestotheWebserver.AJavadeveloperskit isavailable,freeofcharge,fromhttp://java.sun.com.ThefollowingisanexampleHTMLscriptandhighlightedJavaScript.Figure
26.2givesthebrowseroutput.
FIGURE26.2 ExamplewindowfromexampleJavaScript
26.2JavaScriptlanguageProgramming languages can either be compiled to produce an executableprogramor they can be interpretedwhile the user runs the program. Java is aprogramlanguagewhichneedstobecompiledbeforeitisused.Itthuscannotbeused unless the user has the required Java compiler. JavaScript, on the otherhand, is a languagewhich is interpreted by the browser. It is similar inmanywaystoJavabutallowstheusertoembedJava-likecodeintoanHTMLpage.JavaScriptsupportsasmallnumberofdatatypesrepresentingnumeric,Boolean,and string values and is supported bymostmodernWWWbrowsers, such asMicrosoftInternetExplorerandNetscape.HTMLisusefulwhenpagesareshortanddonotcontainexpressions,loopsor
decisions. JavaScript allowsmost of the functionalityof ahigh-level languagefordevelopingclientandserverInternetapplications.Itcanbeusedtorespondtousereventssuchasmouseclicks,forminput,andpagenavigation.AmajoradvantagethatJavaScripthasoverHTMListhatitsupportstheuse
of functionswithout any special declarative requirements. It is also simpler tousethanJavabecauseithaseasiersyntax,specializedbuilt-infunctionality,andminimalrequirementsforobjectcreation.Important concepts in Java and JavaScript are objects.Objects are basically
containersforvalues.ThemaindifferencesbetweenJavaScriptandJavaare:•JavaScriptisinterpretedbytheclient,whileJavaiscompiledontheserver
beforeitisexecuted.•JavaScriptisembeddedintoHTMLpages,whileJavaappletsaredistinct
fromHTMLandaccessedfromHTMLpages.•JavaScripthasloosetypingforvariables(thatis,avariablesdatatypedoes
nothavetobedeclared),whileJavahasstrongtyping(thatis,avariablesdatatypemustalwaysbedeclaredbeforeitisused).
•JavaScripthasdynamicbindingwhereobjectreferencesarecheckedatrun-time.Javahasstaticbindingwhereobjectreferencesmustexistatcompile-time.
26.3JavaScriptvalues,variablesandliteralsJavaScript values, variables and literals are similar to the C programminglanguage.Theirsyntaxisdiscussedinthissection.
26.3.1ValuesThefourdifferenttypesofvaluesinJavaScriptare:•Numericvalue,suchas12or91.5432.•BooleanvalueswhichareeitherTRUEorFALSE.•Stringtypes,suchas‘FredBloggs’.•AspecialkeywordforaNULLvalueNumeric values differ from those in most programming languages in that
there is no explicit distinction between a real value (such as 91.5432) and aninteger(suchas12).
26.3.2DataTypeConversion
JavaScriptdiffersfromJavainthatvariablesdonotneedtohavetheirdatatypesdefined when they are declared (loosely typed). Data types are thenautomatically converted during the execution of the program. Thus a variablecouldbedeclaredwithanumericvalueas:
andtheninthesamescriptitcouldbeassignedastringvalue,suchas:
Theconversionbetweennumericvaluesandstrings inJavaScript iseasy,asnumericvaluesareautomaticallyconvertedtoanequivalentstring.Forexample:
Samplerun26.1givestheoutputfromthisscript.Itcanbeseenthatxandyhavebeenconvertedtoastringvalue(inthiscase,“13”and“10”)andthatx+yin the string conversion statement has been converted to “1310”. If amathematical operation is carried out (z=x+y) then z will contain 23 after thestatementisexecuted.
JavaScript provides several special functions for manipulating string andnumericvalues:•Theeval(string)functionwhichconvertsastringtoanumericalvalue.•TheparseInt(string[,radix])functionwhichconvertsastringintoan
integerofthespecifiedradix(numberbase).Thedefaultradixisbase–10.•TheparseFloat(string)functionwhichconvertsastringintoafloating-point
value.
26.3.3VariablesVariables are symbolic names for values within the script. A JavaScriptidentifier must either start with a letter or an underscore (‘_’), followed byletters,anunderscoreoranydigit(0–9).LikeC,JavaScriptiscasesensitivesothatvariableswiththesamecharactersequencebutwithdifferentcasesforoneormorecharactersaredifferent.Thefollowingaredifferentvariablenames:
26.3.4VariableScopeAvariablecanbedeclaredbyeithersimplyassigningitavalueorbyusingthevar keyword. For example, the following declares to variables Valuel andValue2:
Avariabledeclaredwithinafunctionistakenasalocalvariableandcanonlybeusedwithin that function.Avariabledeclaredoutsideafunction isaglobalvariable and canbeused anywhere in the script.Avariablewhich is declaredlocallywhichisalreadydeclaredasglobalvariableneedstobedeclaredwiththevarkeyword,otherwisetheuseofthekeywordisoptional.
26.3.5LiteralsLiteralvalueshavefixedvalueswithinthescript.Variousreservedformscanbe
usedtoidentifyspecialtypes,suchashexadecimalvalues,exponentformat,andsoon.Withanintegerthefollowingareused:•Ifthevalueisprecededbya0xthenthevalueisahexadecimalvalue(thatis,
base16).Examplesofhexadecimalvaluesare0×1FFF,0xCB.•Ifthevalueisprecededbya0thenthevalueisanoctalvalue(thatis,base8).
Examplesofoctalvaluesare0777,010.•Ifitisnotprecededbyeithera0xora0thenitisadecimalinteger.
Floating-pointvaluesFloating-pointvaluesaretypicallyrepresentedasarealvalue(suchas1.342)orinexponentformat.Someexponentformatvaluesare:
Value Exponentformat
0.000001 le-6
1342000000 1.342e9
BooleanThetrueandfalseliteralsareusedwithBooleanoperations.
StringsIn C a string is represented with double quotes (“str”) whereas JavaScriptaccepts a string within double (“) or single (‘) quotationmarks. Examples ofstringsare:
26.4ExpressionsandoperatorsTheexpressionsandoperatorsused inJavaandJavaScriptarebasedonCandC++. This section outlines the main expressions and operators used inJavaScript.
26.4.1ExpressionsAs with C, expressions are any valid set of literals, variables, operators and
expressions that evaluate to a single value. There are basically two types ofexpression,onewhichassignsavaluetoavariableandtheotherwhichsimplygivesasinglevalue.Asimpleassignmentis:
whichassignsthevalueof21tovalue(notethattheresultoftheexpressionis21).TheresultfromaJavaScriptexpressioncaneitherbe:•Anumericvalue.•Astring.•Alogicalvalue(trueorfalse).
26.5JavaScriptoperatorsBoth Java and JavaScript have a rich set of operators, ofwhich there are fourmaintypes:•Arithmetic.•Logical.•Bitwise.•Relational.
26.5.1ArithmeticArithmetic operators operate on numerical values. The basic arithmeticoperationsareadd(+),subtract(–),multiply(*),divide(/)andmodulusdivision(%).Modulusdivisiongivestheremainderofanintegerdivision.Thefollowinggivesthebasicsyntaxoftwooperandswithanarithmeticoperator.
Theassignmentoperator(=)isusedwhenavariable‘takesonthevalue’ofanoperation.Other short-handed operators are usedwith it, including add equals(+=),minusequals(–=),multipliedequals(*=),divideequals(/=)andmodulusequals(%=).Thefollowingexamplesillustratetheiruses.
Statement Equivalent
x+=3.0 x=x+3.0
voltage/=sqrt(2) voltage=voltage/sqrt(2)
bitmask*=2 bitmask=bitmask*2
Inmanyapplicationsitisnecessarytoincrementordecrementavariableby1.For this purpose Java has two special operators; ++ for increment and –– fordecrement.Thesecaneitherprecedeorfollowthevariable.Iftheyprecede,thena pre-increment/decrement is conducted, whereas if they follow it, a post-increment/decrementisconducted.Thefollowingexamplesshowtheirusage.
Statement Equivalent
no_values++ novalues=novalues+1
i–– i=i-l
Table26.1summarizesthearithmeticoperators.
Table26.1Arithmeticoperators
Operator Operation Example
- subtractionorminus 5–4→1
+ addition 4+2→6
* multiplication 4*3→12
/ division 4/2→2
% modulus 13%3→1
+= addequals χ+=2isequivalenttox=x+2
-= minusequals x-=2isequivalenttox=x–2
/= divideequals x/=yisequivalenttox=x/y
*= multipliedequals x*=32isequivalenttox=x*32
= assignment x=1
++ increment Count++isequivalenttoCount=Count+1
decrement Sec–-isequivalenttoSec=Sec-l
26.5.2RelationshipThe relationship operators determine whether the result of a comparison isTRUEorFALSE.Theseoperatorsaregreaterthan(>),greaterthanorequalto
(<=),lessthan(<),lessthanorequalto(>=),equalto(==)andnotequalto(!=).Table26.2liststherelationshipoperators.
Table26.2Relationshipoperators
26.5.3Logical(TRUEOrFALSE)A logical operation is one in which a decision is made as to whether theoperation performed is TRUE or FALSE. If required, several relationshipoperationscanbegroupedtogethertogivetherequiredfunctionality.Cassumesthatanumericalvalueof0(zero)isFALSEandthatanyothervalueisTRUE.Table26.3liststhelogicaloperators.
Table26.3Logicaloperators
The logicalAND operationwill yield a TRUE only if all the operands areTRUE.Table26.4gives the resultof theAND(&&)operator for theoperationA&&B.ThelogicalORoperationyieldsaTRUEifanyoneoftheoperandsisTRUE.Table26.4givesthelogicalresultsoftheOR(||)operatorforthestatementA||B
andalsogivesthelogicalresultoftheNOT(!)operatorforthestatement!A.
Table26.4Logicaloperations
26.5.4BitwiseThebitwiselogicaloperatorsworkconceptuallyasfollows:•Theoperandsareconvertedto32-bitintegers,andexpressedaseriesofbits
(zerosandones).•Eachbitinthefirstoperandispairedwiththecorrespondingbitinthesecond
operand:firstbittofirstbit,secondbittosecondbit,andsoon.•Theoperatorisappliedtoeachpairofbits,andtheresultisconstructed
bitwise.Thebitwiseoperatorsaresimilartothelogicaloperatorsbuttheyshouldnot
beconfusedastheiroperationdiffers.Bitwiseoperatorsoperatedirectlyontheindividualbitsofanoperand(s),whereaslogicaloperatorsdeterminewhetheraconditionisTRUEorFALSE.Numerical values are stored as bit patterns in either an unsigned integer
format,signedinteger(2’scomplement)orfloating-pointnotation(anexponentandmantissa).CharactersarenormallystoredasASCIIcharacters.ThebasicbitwiseoperationsareAND(&),OR(|),1scomplementorbitwise
inversion(~),XOR(⁁),shift left(<<)andshiftright(>>).Table26.5givestheresultsoftheANDbitwiseoperationontwobitsBit1andBit2.
Table26.5Bitwiseoperations
The Boolean bitwise instructions operate logically on individual bits. TheXORfunctionyieldsa1when thebits inagivenbitpositiondiffer, theANDfunction yields a 1 only when the given bit positions are both 1’s. The ORoperationgivesa1whenanyoneofthegivenbitpositionsarea1.Forexample:
Toperformbitshifts,the<<,>>and>>>operatorsareused.Theseoperatorsshiftthebitsintheoperandbyagivennumberdefinedbyavaluegivenontheright-handsideoftheoperation.Theleftshiftoperator(<<)shiftsthebitsoftheoperand to the left and zeros fill the result on the right. The sign-propagatingrightshiftoperator(>>)shiftsthebitsoftheoperandtotherightandzerosfilltheresultiftheintegerispositive;otherwiseitwillfillwith1s.Thezero-filledrightshiftoperator(>>>)shiftsthebitsoftheoperandtotherightandfillstheresultwithzeros.Thestandardformatis:
26.5.5PrecedenceThereareseveralrulesfordealingwithoperators:•Twooperators,apartfromtheassignment,shouldneverbeplacedsideby
side.Forexample,x*%3isinvalid.•Groupingsareformedwithparentheses;anythingwithinparentheseswillbe
evaluatedfirst.Nestedparenthesescanalsobeusedtosetpriorities.•Aprioritylevelorprecedenceexistsforoperators.Operatorswithahigher
precedenceareevaluatedfirst;iftwooperatorshavethesameprecedence,thentheoperatorontheleft-handsideisevaluatedfirst.The
prioritylevelsforoperatorsareasfollows:
Theassignmentoperatorhasthelowestprecedence.
26.5.6ConditionalExpressionsConditional expressions can result in oneof twovalues baseddependingon acondition.Thesyntaxis:
Iftheexpressionistruethenvaluelisexecutedelsevalue2isexecuted.Forexample:
Thiswillassignthestring‘positive’tosignifthevalueofvalisgreaterthanorequalto0,elseitwillassign‘negative’.
26.5.7StringOperatorsThenormalcomparisonoperators,suchas<,>,>=,==,andsoon,canbeusedwith strings. In addition, the concatenation operator (+) can be used toconcatenatetwostringvaluestogether.Forexample:
willresultinthestring
26.6JavaScriptstatementsJavaScript statements are similar toCandallowagreat deal of control of theexecutionofascript.Thebasiccategoriesare:•Conditionalstatements,suchasif…else.•Repetitivestatements,suchasfor,while,breakandcontinue.•Comments,usingeithertheC++styleforsingle-linecomments(//)or
standardCmulti-linecomments(/*…*/).•Objectmanipulationstatementsandoperators,suchasfor…in,new,
this,andwith.
26.7ConditionalstatementsConditionalstatementsallowaprogramtomakedecisionsontheroutethroughaprogram.
26.7.1If…ElseA decision is made with the if statement. It logically determines whether aconditionalexpressionisTRUEorFALSE.ForaTRUE,theprogramexecutesone block of code; a FALSE causes the execution of another (if any). Thekeywordelse identifies the FALSEblock.Braces are used to define the startandendoftheblock.Relationship operators (>,<,>=,<=,==, ! =) yield a TRUE or FALSE from
theiroperation.Logicalstatements(&&,||,!)canthengroupthesetogethertogivetherequiredfunctionality.If theoperationisnotarelationship,suchasbitwiseoranarithmeticoperation,thenanynon-zerovalueisTRUEandazeroisFALSE.Thefollowingisanexamplesyntaxoftheifstatement.Ifthestatementblock
hasonlyonestatementthebraces({})canbeexcluded.
Thefollowingisanexampleformatwithanelseextension.
Itispossibletonestif…elsestatementstogivearequiredfunctionality.Inthenextexample,statementblock1isexecutedifexpression1isTRUE.IfitisFALSE then the program checks the next expression. If this is TRUE theprogramexecutesstatementblock2,elseitchecksthenextexpression,andsoon.IfallexpressionsareFALSEthentheprogramexecutesthefinalelsestatementblock,inthiscase,statementblock4:
26.8Loops26.8.1For()Manytaskswithinaprogramarerepetitive,suchaspromptingfordata,countingvalues, and soon.Thefor loopallows theexecutionofablockofcode foragivencontrolfunction.Thefollowingisanexampleformat;ifthereisonlyonestatementintheblockthenthebracescanbeomitted.
where:
startingcondition — thestartingvaluefortheloop;
testcondition — iftestconditionisTRUEtheloopwillcontinueexecution;
operation — theoperationconductedattheendoftheloop.
26.8.2While()Thewhile() statementallowsablockofcode tobeexecutedwhilea specifiedcondition is TRUE. It checks the condition at the start of the block; if this isTRUEtheblockisexecuted,elseitwillexittheloop.Thesyntaxis:
If the statement block contains a single statement then the braces may beomitted(althoughitdoesnoharmtokeepthem).
26.9CommentsComments are authornotations that explainwhat a scriptdoes.Comments areignoredbytheinterpreter.JavaScriptsupportsJava-stylecomments:•Commentsonasinglelineareprecededbyadouble-slash(//).•Multilinecommentscanbeprecededby/*andfollowedby*/.Thefollowingexampleshowstwocomments:
26.10Functions
JavaScriptsupportsmodulardesignusingfunctions.AfunctionisdefinedwithaJavaScriptwiththefunctionreservedwordandthecodewithinthefunctionisdefinedwithincurlybrackets.Thestandardformatis:
wheretheparameters(param1,param2,andsoon)arethevaluespassedintothefunction.Notethatthereturnvalue(val)fromthefunctionisonlyrequiredwhenavalueisreturnedfromthefunction.JavaScript26.2givesanexamplewithtwofunctions(add()andmult()).In
this case the values value1 and value2 are passed into the variables a and bwithin the add() function, the result is then sent back from the function intovalue3.
Table26.6ExampleJavaScript
26.11ObjectsandpropertiesJavaScript is based on a simple object-oriented paradigm,where objects are aconstructwithpropertiesthatareJavaScriptvariables.Eachobjecthaspropertiesassociatedwithitandcanbeaccessedwiththedotnotation,suchas:
26.12DocumentobjectsThe document object contains information on the currently opened document.HTML expressions can be displayed with the document.write() ordocument.writeln()functions.Thestandardformatis:
whichdisplaysoneormoreexpressionstothespecifiedwindow.Todisplaytothecurrentwindowthedocument.write()isused.Ifadisplaytoaspecifiedwindowthenthewindowreferenceisdefined,forexample:
isusedtooutputtothemywinwindow.The document object can also be used to display HTML properties. The
standardHTMLformatis:
TheseandotherpropertiescanbeaccessedwithinaJavaScriptwith:
Table26.7showsanexample.
Table26.7ExampleJavaScript
26.13EventhandlingJavaScripthaseventhandlerswhich,onacertainevent,causesotherevents tooccur.Forexample,ifauserclicksthemousebuttononacertainmenuoptionthen the event handler can be made to carry-out a particular action, such asaddingtonumberstogether.Table26.8outlinessomeeventhandlers.
Table26.8Exampleeventhanders
26.14WindowobjectsThewindowobjectisthetop-levelobjectfordocumentsandcanbeusedtoopenandclosewindows.
26.14.1WindowAlertThealertwindowshowsanalertmessagetotheusers.Itsformatis:
Table26.9ExampleJavaScript
26.14.2OpeningAndClosingWindowsWindows are opened with window.open() and closed with window.close().Examplesare:
or to open a window it is possible to simply use open() and to close thecurrentwindowtheclose()functionisused.Thestandardformatis:
wherewinVar is thenameofanewwindowwhichcanbeused to refer toagiven
window.winNameisthewindownamegiventothewindow;featuresisacomma-separatedlistwithanyofthefollowing:
26.14.3WindowConfirmThewindowconfirmisusedtodisplayaconfirmdialogueboxwithaspecifiedmessageandtheOKandCancelbuttons.IftheuserselectstheOKbuttonthenthe function returns a TRUE, else it returns a FALSE. Table 26.10 gives anexample of the confirmwindow. In this casewhen theExit button is selectedthenthefunctionConfirmExit() iscalled.In thisfunctiontheuser isaskedtoconfirm the exit with the confirm window. If the user selects OK then thewindowisclosed(ifitistheonlywindowopenthenthebrowserquits).
Table26.10ExampleJavaScriptwithconfirmwindow
26.14.4WindowPromptThewindowpromptdisplaysapromptdialogboxwhichcontainsamessageandaninputfield.Itsstandardformatis:
26.15Objectmanipulationstatementsandoperators
JavaScript has several methods in which objects can be manipulated. Theseinclude: the new operator, the this keyword, thefor…in statement, and thewithstatement.
26.15.1ThisKeywordThethiskeywordisusedtorefertothecurrentobject.Thegeneralformatis:
JavaScript 26.5 gives an example of the this keyword. In this case this isused to pass the property values of the input form. This is then passed to thefunctioncheckval()whentheonBlureventoccurs.
26.15.2NewOperatorThenewoperator isused todefineanewuser-definedobject typeorofoneofthe pre-defined object types, such as array, Boolean, date, function andmath.JavaScript26.6givesanexamplewhichcreatesanarrayobjectwith6elementsandthenassignsstringstoeachofthearray.NotethatinJavathefirstelementofthearrayisindexedas0.
Typicallythenewoperatorisusedtocreatenewdataobjects.Forexample:
26.15.3For…InThefor…instatementisusedtoiterateavariablethroughallitsproperties.Ingeneralitsformatis:
26.15.4WithThe with statement defines a specified object for a set of statements. Awithstatementlooksasfollows:
For example JavaScript 26.7 contains calls to the Math object for the PIpropertyandcosandsinmethods.JavaScript26.8thenusesthewithstatementtodefinetheMatchobjectisthedefaultobject.
26.16Exercises26.16.1.ExplainhowJavadiffersfromJavaScript.26.16.2.ExplainthemainadvantagesofusingJavaratherthanahigh-level
language,suchasC++orPascal.26.16.3.ImplementtheJavaScriptsinthetextandtesttheiroperation.26.16.4.WriteaJavaScriptinwhichtheuserentersavalueandthescript
calculatesthesquareofthatvalue.26.16.5.WriteaJavaScriptinwhichtheuserinitiallyenterstheirname.The
scriptshouldthentesttheenterednameandifitisnot‘FRED’,‘BERT’or‘FREDDY’thenthebrowserexits.
27
Java(Introduction)
27.1Introduction
Java has the great advantage over conventional software languages in that itproduces code which is computer hardware independent. This is because thecompiled code (called bytecodes) is interpreted by the WWW browser.Unfortunatelythisleadstoslowerexecution,butasmuchofthetimeisspentingraphicaluser interfaceprograms, toupdate thegraphics, thentheoverheadis,asfarastheuserisconcerned,notagreatone.The other advantages that Java has over conventional software languages
include:•ItisamoredynamiclanguagethanC/C++andPascal,andwasdesignedto
adapttoanevolvingenvironment.Itisextremelyeasytoaddnewmethodsandextralibrarieswithoutaffectingexistingapplets.ItisalsousefulinInternetapplicationsasitsupportsmostofthestandardimageaudioandvideoformats.
•Ithasnetworkingfacilitiesbuiltintothelanguage(supportforTCP/IPsockets,URLs,IPaddressesanddatagrams).
•WhileJavaisbasedonCandC++itavoidssomeofthedifficultareasofC/C++code(suchaspointersandparameterpassing).
•Itsupportsclient/serverapplicationswheretheJavaappletsrunontheserverandtheclientreceivestheupdatedgraphicsinformation.InthemostextremecasetheclientcansimplybeagraphicsterminalwhichrunsJavaappletsoveranetwork.Thesmall‘black-box’networkedcomputerisoneofthefoundingprinciplesofJava,anditishopedinthefuturethatsmallJava-basedcomputerscouldreplacethecomplexPC/workstationforgeneralpurposeapplications,likeaccessingtheInternetorplayingnetworkgames.This‘black-box’computerconceptisillustratedinFigure27.1.
FIGURE27.1 Internetaccessing
Most existingWeb browsers are enabled for Java applets (such as InternetExplorer3.0andNetscape2.0andlaterversions).Figure27.2showshowJavaappletsarecreated.Firstthesourcecodeisproducedwithaneditor,nextaJavacompilercompilestheJavasourcecodeintobytecode(normallyappendingthefile name with .class). An HTML page is then constructed which has thereference to theapplet.After thisa Java-enabledbrowserorappletviewercanthenbeusedtoruntheapplet.
FIGURE27.2 ConstructingJavaapplets
TheJavaDevelopmentKit (JDK) isavailable, free, fromSunMicrosystemsfrom the WWW site http://java.sun.com. This can be used to compile Javaappletsandstandaloneprograms.ThereareversionsforWindowsNT/95,MacorUNIX-basedsystemswithmanysampleapplets.Table27.1showsthemainfilesusedinthePCversion.Figure27.3showsthe
directory structure of the JDK tools. The Java compiler, Java interpreter andappletviewerprogramsarestoredinthebindirectory.OnthePC,thisdirectory
isnormallysetupinthePATHdirectory,sothattheJavacompilercanbecalledwhiletheuserisinanotherdirectory.Thefollowingisatypicalsetup(assumingthatthehomedirectoryisC:\JAVA):
Table27.1JDKprograms
File Description
Javac.exe Javacompiler
Java.exe Javainterpreter
Appletviewer.exe Appletviewerfortestingandrunningapplets
classes.zip Itisneededbythecompilerandinterpreter
javap.exe Javaclassdisassembler
javadoc.exe Javadocumentgenerator
jbd.exe Javadebugger
FIGURE27.3 DirectorystructureofJDK
Thelibdirectorycontainstheclasses.zipfilewhichisazipped-upversionof the Javaclass files.These class files are stored in thedirectoriesbelow thesrc/java directory. For example, the io classes (such as File.java andInputStream.java) are used for input/output in Java, theawt classes (such asPanel.javaandDialog.java)areusedtocreateandmaintainwindows.Theseandotherclasseswillbediscussedlater.Theincludedirectorycontainsheader files for integratingC/C++programs
withJavaappletsandthedemodirectorycontainssomesampleJavaapplets.
27.1.1AppletTagAnappletiscalledfromwithinanHTMLscriptwiththeAPPLETtag,suchas:
whichloadsanappletcalledTest.classandsets theappletsize to200pixelswideand300pixelshigh.Table27.2discussessomeoptionalparameters.
Table27.2OtherappletHTMLparameters
27.1.2AppletViewerAusefulpartoftheJDKtoolsisanappletviewerwhichisusedtotestappletsbefore theyare runwithin thebrowse.Theappletvieweron thePCversion isAppletViewer.exeandthesuppliedargumentistheHTMLfilethatcontainstheapplettag(s).Itthenrunsalltheassociatedappletsinseparatewindows.
27.2CreatinganappletJavaapplet27.1showsasimpleJavaappletwhichdisplaystwolinesoftextandHTMLscript27.1showshowtheappletintegratesintoanHTMLscript.First the Java applet (j1.java) is created. In this case the edit program is
used.Thedirectory listingbelow shows that the files created arej1.java andj1.html(NotethatWindowsNT/95displaysthe8.3filenameformatonthelefthandsideofthedirectorylistingandthelongfilenameontherighthandside).
NexttheJavaappletiscompiledusingthejavac.exeprogram.Itcanbeseenfromthelistingthat,iftherearenoerrors,thecompiledfileisnamedj1.class.Thiscanthenbeused,withtheHTMLfile,torunasanapplet.
27.3AppletbasicsJavaapplet27.1recapsthepreviousJavaapplet.ThissectionanalyzesthemainpartsofthisJavaapplet.
27.3.1ImportStatementsThe import statement allows previously written code to be included in theapplet.Thiscode is stored inclass libraries (orpackages),whicharecompiledJavacode.FortheJDKtools,theJavasourcecodefortheselibrariesisstoredinthesrc/javadirectory.EachJavaappletcreatedbeginswith:
Theseincludetheawtandappletclasslibraries.Theawtclassprovidecodethat handles windows and graphics operations. The applet in Java script 27.1usesawtcode, forexample,displays the ‘This is ..’messagewithin theappletwindow. Likewise the applet uses the applet code to let the browser run theapplet.ThedefaultJavaclass librariesarestored in theclasses.zip file in thelib
directory.Thisfileisinacompressedformandshouldnotbeunzipbeforeitisused.Thefollowingisanoutlineofthefile.
ItcanbeseenthatupgradingtheJavacompilerissimple,asallthatisrequiredistoreplacetheclasslibrarieswithnewones.Forexample,ifthebasiclanguageisupgraded thenjava.lang.* files issimplyreplacedwithanewversion.Theuser can also easily add new class libraries to the standard ones. A completelistingoftheclassesisgiveninAppendixA.
27.3.2AppletClassThestartoftheappletcodeisdefinedintheform:
whichinformstheJavacompilertocreateanappletnamedj1thatextendstheexistingApplet class.Thepublickeywordat the startof the statementallowsthe Java browser to run the applet, while if it is omitted the browser cannotaccessyourapplet.Theclasskeyword isused tocreatingaclassobjectnamedj1 thatextends
theappletclass.Afterthistheappletisdefinedbetweentheleftandrightbraces(groupingsymbols).
27.3.3AppletFunctions
FunctionsallowJavaappletstobesplit intosmallersub-taskscalledfunctions.Thesefunctionshavetheadvantagethat:•Theyallowcodetobereused.•Theyallowfortop-leveldesign.•Theymakeappletdebuggingeasieraseachfunctioncanbetestedinisolation
totherestoftheapplet.Afunctionhasthepublickeyword,followedbythereturnvalue(ifany)and
the name of the function.After this the parameters passed to the function aredefinedwithinroundedbrackets.Recappingfromthepreviousexample:
This functionhas thepublickeywordwhichallowsanyuser toexecute thefunction.Thevoidtypedefinesthatthereisnothingreturnedfromthisfunctionandthenameofthefunctionispaint().Theparameterpassedintothefunctionis g which has the data type of Graphics. Within the paint() function thedrawstring()functioniscalled.Thisfunctionisdefinedinjava.awt.Graphicsclass library (this library has been included with the import java.awt. *statement.Thedefinitionforthisfunctionis:
whichdrawsastringofcharactersusingthecurrentfontandcolour.Thex,ypositionisthestartingpointofthebaselineofthestring(str).It should be noted that Java is case sensitive and the names givenmust be
referedtointhecasethattheyaredefinedas.
27.4Stand-aloneprogramsAJavaprogramcanalsoberunasastand-aloneprogram.ThisallowstheJavaprogramtoberunwithoutabrowserandisnormallyusedwhentestingaJavaapplet.Themethodofoutputtothescreenis:
which prints amessage (message) to the display.This type of debugging ismessy as these statements need to be manually inserted in the program. It islikely that later versions of the JDK toolkit will contain a run-time debuggerwhichwillallowdeveloperstoviewtheexecutionoftheprogram.Torunastand-aloneprogramthejava.exeprogramisusedandtheuseradds
outputstatementswiththeSystem.out.println()function.NotethatthereisnooutputfromappletwiththeSystem.out.println()function.Java stand-alone program 27.1 gives a simple example of a stand-alone
program.Thepublicstaticvoidmain(Strings[]args)definesthemainfunction.Sample run27.3 showshow the Javaprogram iscreated (withedit)andthencompiler(withjavac.exe),andthenfinallyrun(withjava.exe).
27.5JavareservedwordsLikeanyprogramminglanguage,Javahasvariousreservedwordswhichcannotbeusedasavariablename.Thesearegivennext:
27.6AppletvariablesVariablesareusedtostorednumericvaluesandcharacters.InJavaallvariablesmust be declaredwith their data type before they can be used. The Java datatypesaresimilartoC/C++types,andarestatedinTable27.4.
Table27.4Javadatatypesandtheirrange
Type Storage(bytes) Range
boolean TrueorFalse
byte 1 −128to127
char 2 Alphabeticcharacters
int 4 −2,147,483,648to2,147,483,647
short 2 −32,768to32,767
long 4 −2,147,483,648to2,147,483,647
float 4 ±3.4×10(T−38to±3.4×1038
double 8 ±1.7×10−308to±1.7×10308
27.6.1ConvertingNumericDataTypesJava is a strongly typed language and various operations follow standardconversionsfordatatypes.Ifthedeveloperwantstoconvertfromonedatatypetoanother(suchasfromanintegertoadouble)thenthedatatypeconversionisused where the converted data type is defined within rounded brackets. Forexample:
convertstheadditionofyandztoaninteger.
27.6.2ThePaint()ObjectThepaint()objectistheobjectthatiscalledwhenevertheappletisredrawn.Itwillthusbecalledwhenevertheappletisrunandthenitiscalledwhenevertheappletisredisplayed.
27.7JavaoperatorsThetablebelowrecapstheJavaoperatorsfromthepreviouschapter.
27.8MathematicaloperationsJava has a basic set of mathematics functions which are defined in thejava.lang.Mathclass library.Table27.5outlines thesefunctions.Anexampleofthefunctionsinthislibraryisabs()whichcanbeusedtoreturntheabsolutevalue of either a double, an int or a long value. Java automatically picks therequired format and the return data type will be of type of the value to beoperatedon.
Table27.5Functionsdefinedinjava.lang.Math
Function Description
doubleabs(doublea) Returnstheabsolutedoublevalueofa.
floatabs(floata) Returnstheabsolutefloatvalueofa.
intabs(inta) Returnstheabsoluteintegervalueofa.
longabs(longa) Returnstheabsolutelongvalueofa.
doubleacos(doublea) Returnsthearccosineofa,intherangeof0.0throughPi.
doubleasin(doublea) Returnsthearcsineofa,intherangeofPi/2throughPi/2.
doubleatan(doublea) Returnsthearctangentofa,intherangeof–Pi/2throughPi/2.
doubleatan2(doublea,
doubleb)
Convertsrectangularcoordinates(a,b)topolar(r,theta).
doubleceil(doublea) Returnsthe’ceiling’orsmallestwholenumbergreaterthanorequaltoa.
doublecos(doublea) Returnsthetrigonometriccosineofanangle.
doubleexp(doublea) Returnstheexponentialnumbere(2.718…)raisedtothepowerofa.
doublefloor(doublea) Returnsthe’floor’orlargestwholenumberlessthanorequaltoa.
double
IEEEremainder(double
f1,doublef2)
Returnstheremainderoff1dividedbyf2asdefinedbyIEEE754.
doublelog(doublea) Returnsthenaturallogarithm(basee)ofa.
doublemax(doublea,
doubleb)
Takestwodoublevalues,aandb,andreturnsthegreaternumberofthetwo.
doublemax(floata,float
b)
Takestwofloatvalues,aandb,andreturnsthegreaternumberofthetwo.
intmax(inta,intb) Takestwointvalues,aandb,andreturnsthegreaternumberofthetwo.
max(longa,longb) Takestwolongvalues,aandb,andreturnsthegreaternumberofthetwo.
doublemin(doublea,
doubleb)
Takestwodoublevalues,aandb,andreturnsthesmallestnumberofthetwo.
floatmin(floata,float
b)
Takestwofloatvalues,aandb,andreturnsthesmallestnumberofthetwo.
intmin(inta,intb) Takestwointegervalues,aandb,andreturnsthesmallestnumberofthetwo.
longmin(longa,longb) Takestwolongvalues,aandb,andreturnsthesmallestnumberofthetwo.
doublepow(doublea,
doubleb)
Returnsthenumberaraisedtothepowerofb.
doublerandom() Generatesarandomnumberbetween0.0and1.0.
doublerint(doubleb) Convertsadoublevalueintoanintegralvalueindoubleformat.
longround(doublea) Roundsoffadoublevaluebyfirstadding0.5toitandthenreturningthelargestintegerthatislessthanorequaltothisnewvalue.
intround(floata) Roundsoffafloatvaluebyfirstadding0.5toitandthenreturningthelargestintegerthatislessthanorequaltothisnewvalue.
doublesin(doublea) Returnsthetrigonometricsineofanangle.
doublesqrt(doublea) Returnsthesquarerootofa.
doubletan(doublea) Returnsthetrigonometrictangentofanangle.
Asthefunctionsarepartof theMathclass theyareprecededwith theMath.
classmethod.Forexample:
Java stand-alone program 27.2 shows a few examples of mathematicaloperationsandSamplerun27.4showsasamplecompilationandrunsession.Javahasalsotwopre-definedmathematicalconstants.Theseare:•Piisequivalentto3.14159265358979323846.•Eisequivalentto2.7182818284590452354.
27.9Loops
27.9.1For()AswithC/C++andJavaScriptthestandardformatforafor()loopis:
where:
Javaapplet27.2 showshowafor() loopcanbeused todisplay thesquareandcubeof thevalues from0 to9.Notice that the finalvalueofiwithin thefor()loopis9becausetheendconditionisi<10(whileiislessthan10).
27.9.2While()Thewhile()statementallowsablockofcodetobeexecutedwhileaspecifiedcondition is TRUE. It checks the condition at the start of the block; if this isTRUEtheblockisexecuted,elseitwillexittheloop.Thesyntaxis:
If the statement block contains a single statement then the braces may beomitted(althoughitdoesnoharmtokeepthem).
27.10ConditionalstatementsConditionalstatementsallowaprogramtomakedecisionsontheroutethroughaprogram.
27.10.1If…ElseAswithC/C++andJavaScriptthestandardformatforaif()descisionis:
Thefollowingisanexampleformatwithanelseextension.
Javaapplet27.3usesafor()loopandtheif()statementtotestifavalueislessthan,equaltoorgreaterthan5.Theloopisusedtorepeatthetest10times.
The random() function is used to generate a value between 0 and 1, thereturnedvalueisthenmultipliedby10soastoconverttointoavaluebetween0and10.Thenitisconvertedtoanintegerusingthedatatypemodifier(int).Theif()statementisthenusedtotestthevalue.
27.11Exercises27.11.1.WriteaJavaappletwhichdisplaysthefollowingtableofpowers.
27.11.2.WriteaJavaappletwhichdisplaysthefollowingtableofsquarerootvaluesfrom1to15.
Value Squareroot
1 1
2 1.414214
3 1.732051
4 2
5 2.236068
6 2.44949
7 2.645751
8 2.828427
9 3
10 3.162278
11 3.316625
12 3.464102
13 3.605551
14 3.741657
15 3.872983
27.11.3.WriteaJavaappletwhichdisplay20randomnumbersfrombetween0and20.
27.11.4.WriteaJavaappletthatsimulatestherollingoftwodice.Asampleoutputis:
Dice1: 3
Dice2: 5
Total: 8
28
Java(Extendedfunctions)
28.1Introduction
Chapter27discussedtheJavaprogramminglanguage.Thischapterinvestigatesevent-drivenprograms.Themaineventsare:•Initializationandexitfunctions(init(),start(),stop()anddestroy
()).•Repaintingandresizing(paint()).•Mouseevents(mouseUp(),mouseDown()andmouseDrag()).•Keyboardevents(keyUp()andkeyDown()).
28.2InitializationandexitfunctionsJavahasvariousreservedfunctionswhicharecalledwhenvariouseventoccur.Table 28.1 shows typical initialization functions and their events, and Figure28.1illustrateshowtheyarecalled.
Table28.1Javainitializationandexitfunctions
Function Description
publicvoid
init()
Thisfunctioniscalledeachtimetheappletisstarted.Itistypicallyusedtoadduser-interfacecomponents.
publicvoid
start()
Thisfunctioniscalledaftertheinit()functioniscalled.Itisalsocalledwhenevertheuserreturnstothepagecontainingtheappletandthuscanbecalledmanytimesasopposedtotheinit()functionwhichwillonlybecalledwhentheappletisfirststarted.Thus,codewhichistobeexecutedonlyonceisnormallyputintheinit()function,andcodewhichmustbeexecutedeverytimetheappletisaccessedshouldbeinsertedintothestart()function.
publicvoid
stop()
Thisfunctioniscalledwhentheusermovesawayfromthepageonwhichtheappletresides.Itisthustypicallyusedtostopprocessingwhiletheuserisnotaccessingtheapplet.Typicallyitisusedtostopanimationoraudiofiles,ormathematicalprocessing.Thestart()functionnormallyrestartstheprocessing.
publicvoid
paint
(Graphics
g)
Thisfunctioniscalledwhentheappletisfirstcalledandwhenevertheuserresizesormovesthewindows.
publicvoid
destroy()
Thisfunctioniscalledwhentheappletisstoppedandisnormallyusedtoreleaseassociatedresources,suchasfreeingmemory,closingfiles,andsoon.
FIGURE28.1 Javainitializationandexitfunctions
Javaapplet28.1gives an exampleusing theinit() andstart() functions.Thevariablei isdeclaredwithin theappletand it is set toavalueof5 in theinit()function.Thestart()functionthenadds6ontothisvalue.Afterthisthepaint()functioniscalledsothatitdisplaysthevalueofi(whichshouldequal11).
28.3MouseeventsMost Java applets require some user interaction, normally with the mouse orfrom the keyboard. Amouse operation causes mouse events. The three basiceventswhicharesupportedinJavaare:•mouseUp().•mouseDown().•mouseDrag().Java applet 28.2 uses the three mouse events to display the current mouse
cursor.Eachofthefunctionsmustreturnatruevaluetoidentifythattheeventhasbeenhandledsuccessfully(thereturntypeisofdata typeBooleanthus thereturn could only be a true or a false). In the example applet, onmoving themousecursorwiththeleftmousekeypresseddownthemouseDrag()functionisautomaticallycalled.Thexandycoordinateofthecursorisstoredinthexandyvariablewhentheeventoccurs.Thisisusedinthefunctionstobuildamessagestring(inthecaseofthedrageventthestringnameisMouseDragMsg).
28.4MouseselectionInmany applets the user is prompted to select an object using themouse. Toachievethisthexandypositionoftheeventistestedtodetermineifthecursoriswithinthedefinedarea.Javaapplet28.3isaprogramwhichallowstheusertopress themouse button on the applet screen. The applet then uses themouse
eventstodetermineifthecursoriswithinagivenareaofthescreen(inthiscasebetween 10,10 and 100,100). If the user is within this defined area then themessage displayed is HIT, else it is MISS. The graphics functiong.drawRect(x1,y1,x2,y2)drawsarectanglefrom(x1,y1)to(x2,y2).
28.5KeyboardinputJavaprovidesfortwokeyboardevents,theseare:•keyUp().Iscalledwhenakeyhasbeenreleased.•keyDown().Iscalledwhenakeyhasbeenpressed.The parameters passed into these functions are event (which defines the
keyboardstate)andanintegerKeypressedwhichdescribesthekeypressed.
Theeventcontainsanidentificationastothetypeofeventitis.Whenoneofthe function keys is pressed then the variable event.id is set to the macroEvent.KEY_ACTION(asshowninJavaapplet28.5).Otherkeys,suchastheCtrl,AltandShiftkeys,setbitsintheevent.modifiervariable.ThetestfortheCtrlkeyis:
ThisteststheCTRL_MASKbit;ifitisa1thentheCTRLkeyhasbeenpressed.Javaapplet28.5showsitsuses.
ForfunctionkeystheKeyPressvariablehasthefollowingvalues:
Thus,totestforthefunctionkeysthefollowingroutinecanbeused:
ForcontrolkeystheKeyPressvariablehasthefollowingvalues:
Thus,totestforthecontrolkeysthefollowingroutinecanbeused:
28.6GraphicsimagesJavahasexcellentsupportimagesandsound.ForgraphicsfilesithassupportforGIFandJPEGfiles,eachofwhichisinacompressedform.Theimageobjectisdeclaredwith:
Next the graphics image is associated with the image object with the getImage()function:
where the getCodeBase() function returns the applets URL (such aswww.eece.napier.ac.uk)andthesecondargumentisthenameofthegraphicsfile(inthiscase,myson.gif).Afterthistheimagecanbedisplayedwith:
wheremypicisthenameoftheimageobject,andthexandyvaluesarethecoordinates of the upper-left hand corner of the image. The this keywordassociatesthecurrentobject(inthiscaseitisthegraphicsimage)andthecurrentapplet.Javaapplet28.6givesanappletwhichdisplaysanimage.
28.7GraphicsThejava.awt.Graphicsclasscontainsagreatdealofgraphics-basedfunctions;thesearestatedinTable28.2.
Table28.2Javagraphicsfunctions
Graphicsfunction Description
publicabstractvoid
translate(intx,
inty)
Translatesthespecifiedparametersintotheoriginofthegraphicscontext.Allsubsequentoperationsonthisgraphicscontextwillberelativetothisorigin.Parameters:x–thexcoordinatey–theycoordinate
publicabstractColor
get-Color()
Getsthecurrentcolour.
publicabstractvoid
setColor(Colorc)
Setcurrentdrawingcolour.
publicabstractFont
getFont()
Getsthecurrentfont.
publicabstractvoid
setFont(Fontfont)
Setthecurrentfont.
publicFontMetrics
getFontMetrics()
Getsthecurrentfontmetrics.
publicabstract
FontMetrics
getFontMetrics(Font
f)
Getsthecurrentfontmetricsforthespecifiedfont.
publicabstractvoid
copyArea(intx,int
y,intwidth,int
height,intdx,int
dy)
Copiesanareaofthescreenwhere(x,y)isthecoordinateofthetopleft-handcorner,widthandheightandthewidthandheight,anddxisthehorizontaldistanceanddytheverticaldistance.
publicabstractvoid
drawLine(intx1,int
y1,intx2,inty2)
Drawsalinebetweenthe(x1,y1)and(x2,y2).
publicabstractvoid
fillRect(intx,int
y,intwidth,int
height)
Fillsthespecifiedrectanglewiththecurrentcolour.
public
voiddrawRect(int
x,inty,intwidth,
intheight)
Drawstheoutlineofthespecifiedrectangleusingthecurrentcolour.
Publicabstractvoid
clearRect(intx,
inty,intwidth,
intheight)
Clearsthespecifiedrectanglebyfillingitwiththecurrentbackgroundcolourofthecurrentdrawingsurface.
publicvoid
draw3DRect(intx,
inty,intwidth,
intheight,boolean
raised)
Drawsahighlighted3-Drectanglewhereraisedisabooleanvaluethatdefineswhethertherectangleisraisedornot.
publicvoid
fill3DRect(intx,
inty,intwidth,
intheight,boolean
raised)
Paintsahighlighted3-Drectangleusingthecurrentcolour.
publicabstractvoid
drawOval(intx,int
y,intwidth,int
height)
Drawsanovalinsidethespecifiedrectangleusingthecurrentcolour.
publicabstract
voidfillOval(int
x,inty,intwidth,
intheight)
Fillsanovalinsidethespecifiedrectangleusingthecurrentcolour.
publicabstractvoid
drawArc(intx,int
Drawsanarcboundedbythespecifiedrectanglestarting.ZerodegreesforstartAngleisatthe3-o’clockpositionandarcAnglespecifiestheextentofthearc.ApositivevalueforarcAngleindicatesacounter-clockwiserotationwhilea
y,intwidth,int
height,int
startAngle,int
arcAngle)
arc.ApositivevalueforarcAngleindicatesacounter-clockwiserotationwhileanegativevalueindicatesaclockwiserotation.Theparameter(x,y)specifiesthecentrepoint,andwidthandheightspecifiesthewidthandheightofarectangle
publicabstractvoid
fillArc(intx,int
y,intwidth,int
height,int
startAngle,int
arcAngle)
Fillsapie-shapedarcusingthecurrentcolour.
publicabstractvoid
drawPolygon(int
xPoints[],int
yPoints[],int
nPoints)
Drawsapolygonusinganarrayofxandypoints(xPoints[]andyPoints[]).ThenumberofpointswithinthearrayisspecifiedbynPoints.
publicabstractvoid
fillPolygon(int
xPoints[],int
yPoints[],int
nPoints)
Fillsapolygonwiththecurrentcolour.
publicabstractvoid
drawstring(String
str,intχ,inty)
DrawsthespecifiedStringusingthecurrentfontandcolour.
publicabstract
boolean
drawImage(Image
img,intx,inty)
Drawsthespecifiedimageatthespecifiedcoordinate(x,y).
publicabstractvoid
dispose()
Disposesofthisgraphicscontext.
28.7.1SettingTheColourThecurrentdrawingcolour is set using thesetColor() function. It is usedasfollows:
Coloursaredefinedinthejava.awt.Colorclassandvalidcoloursare:
Anyother24-bitcolourcanbegeneratedwith thefunctionColorwhichhastheformat:
wherer,gandbarevaluesofstrengthfrom0to255.Forexample:
28.7.2DrawingLinesAndCirclesNormally to draw a graphics object the user must plan its layout for thedimension within the object. Figure 28.2 shows an example graphic with therequireddimensions.ThedrawOval()functionusesthetoplevelhandpointforthexandyparametersinthefunctionandthewidthandheightdefinethewidthandheightoftheovalshape.ThusthedrawOval()functioncanbeusedtodrawcircles(ifthewidthisequaltotheheight)orovals(ifthewidthisnotequaltotheheight).Javaapplet28.7showstheJavacodetodrawtheobject.Thisappletuses the setColor() function tomake the circle yellow and the other shapesblue.
FIGURE28.2 Dimensionsofgraphic
28.7.3DrawingPolygonsThe drawPolygon() function can be used to draw complex objects where theobjectisdefinedasagroupof(x,y)coordinates.Javaapplet28.8drawsabasicpictureofacarand thexpointsarrayholds thexcoordinatesandypointsholdtheycoordinates.Figure28.3illustratestheobject.
FIGURE28.3 Coordinatesofgraphic
28.8SoundTheplayingofsoundfilesissimilartodisplayinggraphicsfiles.Javaapplet28.9shows a sample applet which plays an audio file (in this case, test.au).Unfortunately the current version of the Java compiler only supports the AUformat,thusWAVfilesneedtobeconvertedintoAUformat.TheinitializationprocessusesthegetAudioClip()functionandtheaudiofile
is played with the loop() function. This function is contained in thejava.applet.AudioClipclass,thesefunctionsare:
28.9DialogboxesOne of the features of Java is that it supports dialog boxes and checkboxes.Theseareusedwitheventhandlerstoproduceevent-drivenoptions.
28.9.1ButtonsAndEventsJavaapplet28.10createsthreeButtonobjects.Thesearecreatedwiththeadd()functionwhichdisplaysthebuttonintheappletwindow.
Applet 28.10 creates three buttonswhich do not have any action associatedwith them. Javaapplet28.11uses theaction functionwhich iscalledwhenaneventoccurs.Withinthisfunctiontheeventvariableistestedtoseeifoneofthebuttonscausedtheevent.Thisisachievedwith:
If this tests to the true then theMsg string takes on thevalueof theObject,whichholdthenameofthebuttonthatcausedtheevent.
28.9.2CheckboxesTypicallycheckboxesareused toselect fromanumberofoptions.Javaapplet28.12showshowanappletcanusecheckboxes.Asbefore,theactionfunctioniscalledwhenacheckboxchangesitsstateandwithinthefunctionevent.targetparameteristestedforthecheckboxwith:
Ifthisistrue,thenthefunctionDetermineCheckState()iscalledwhichtestsevent.targetforthecheckboxvalueanditsstate(trueorfalse).
28.9.3RadioButtonsThe standard checkboxes allowanynumberofoptions tobe selected.A radiobuttonallowsonlyoneoptiontobeselectedatatime.Thepreviousexamplecanbechangedasfollows:
ThissetsthecheckboxtypetoRadioGroupanditcanbeseenthatonlyoneofthecheckboxesisinitallyset(thatis,‘Post’).
28.9.4Pop-UpMenuChoicesTocreateapop-upmenutheChoiceobjectisinitallycreatedwith:
AfterthisthemenuoptionsaredefinedusingtheaddItemmethod.Javaapplet28.13showsanexampleusageofapop-upmenu.
28.9.5TextInputTextcanbeenteredintoaJavaappletusingtheTextFieldaction.InJavaapplet28.14theTextField(20)definesa20-characterinputfield.
28.10FontsJava is well supported with different fonts. The class library java.awt.FontdefinestheFontclassandthegeneralformatfordefiningthefontis:
Themainfont_typesare:
ThisbookiswritteninTimesRoman.Helveticalooksgoodasaheader,suchasHeader1.Courierproducesamonospacefontwhereallofthecharactershavethesamewidth.TheJavaappletsinthischapterusetheCourierfont.Symbolisnormallyusedwhenspecialsymbolsarerequired.Thefont_attribcaneitherbeBOLD,ITALICorNORMAL.andthefont_sizeisanintegervaluewhichissupportedby the compiler. The font size of this text is 11 andmost normal text varies
between8and12.Javaapplet28.15showsanexampleappletusingdifferentfonts.
28.11Exercises28.11.1.Explainhowthethreemouseeventsoccur.28.11.2.WriteaJavaappletthatcontainsatargetwhichhasareaswithdifferent
pointvalues.Thesepointvaluesare50,100and150.Theprogramshouldaccumulatethescoresofar.AsamplescreenisgiveninFigure28.4(refertoJavaapplet28.3fortheoutlineoftheprogram).
FIGURE28.4
28.11.3.Modifytheprogramin28.11.2sothataRESETbuttonisdisplayed.Whenselectedthepointsvalueshouldberesettozero.
28.11.4.WriteaJavaappletwhichdisplaysasquareatastartingposition(50,50)withawidthandlengthof50units.Theusershouldthenbeabletomovetherectangleup,down,leftorrightusingtheukey(forup),dkey(fordown),1key(forleft)andrkey(forright).Theprogramshouldcontinueuntilthexkeyispressed.
28.11.5.WriteaJavaappletwhichdisplayswhichfunctionkeyorcontrolkey(Cntrl)hasbeenpressed.TheprogramshouldruncontinuouslyuntiltheCntrl-Zkeystrokeispressed.
28.11.6.WriteseparateJavaapplets,usingsimplerectanglesandcircles,todisplaythefollowinggraphics:(a)atelevision(asamplegraphicisshowninFigure28.5)
FIGURE28.5
(b)aface(c)ahouse(d)arobot
28.11.7.LocatethreeGIForJPEGfiles.ThenwriteaJavaappletwhichallowstheusertochoosewhichoneshouldbedisplayed.ThefunctionkeyF1selectsthefirstimage,F2thesecond,andF3thethird.ThefunctionkeyF4shouldexittheapplet.
28.11.8.UsinganappletwhichdisplaysthetextTESTTEXT,determinetheapproximatecolourofthefollowingcoloursettings:(a)color(100,50,10)(b)color(200,200,0)(c)color(10,100,100)(d)color(200,200,200)(e)color(10,10,100)
28.11.9.Writeanappletusingapolygonforthefollowingshapes:(a)aship(asampleisshowninFigure28.6)
FIGURE28.6
(b)atank(c)aplane
28.11.10.Locateasoundfileandwriteanapplicationwhichusesit.28.11.11.WriteaJavaappletwhichdisplaysthefollowing:
NotethatSampleAppletisboldArialtextwithasizeof20andtheothertextisCourierofsizeof14.
28.11.12.WriteaJavaappletinwhichtheuserenterssometext.IftheuserentersEXITthentheprogramwillexit.
29
Introduction
29.1Introduction
In1947theinventionofthetransistorcausedagreatrevolution.Infactscientistsat theBellLaboratorieskept its inventionsecret foroversevenmonthsso thatthey could fully understand its operation.On 30 June 1948 the transistorwasfinallyrevealedtotheworld.Unfortunately,aswithmanyothergreatinventions,it received little public attention and even less press coverage (theNew YorkTimesgaveit4½inchesonpage46).Transistorshad, initially,beenmadefromgermanium,which isnota robust
materialandcannotwithstandhightemperatures.Thefirstcompanytoproposeamethod of using silicon transistorswas a geological research company namedTexas Instruments (which had diversified into transistors). Soon manycompanieswereproducing silicon transistors andby1955 the electronicvalvemarket had peaked,while themarket for transistorswas rocketing.The largerelectronic valvemanufacturers, such asWestern Electric, CBS, Raytheon andWestinghouse failed to adapt to the changing market and quickly lost theirmarket share to the new transistor manufacturing companies, such as TexasInstruments,Motorola,HughesandRCA.In 1959, IBM built the first commercial transistorized computer named the
IBM 7090/7094 series. It was so successful that it dominated the computermarket for many years. In 1965, they produced the famous IBM system 360whichwasbuiltwithintegratedcircuits.Thenin1970IBMintroducedthe370system, which included semiconductor memories. Unfortunately, thesecomputerswereextremelyexpensivetopurchaseandmaintain.Around the same time the electronics industrywas producing cheap pocket
calculators. The development of affordable computers happened when theJapanesecompanyBusiconcommissionedasmall,atthetime,companynamedInteltoproduceasetofeighttotwelveICsforacalculator.InsteadofdesigningacompletesetofICs,IntelproducedasetofICswhichcouldbeprogrammedto
perform different tasks. Thesewere the first evermicroprocessors. Soon Intel(short for Integrated Electronics) produced a general-purpose 4-bitmicroprocessor,namedthe4004andamorepowerful8-bitversion,namedthe8080.Other companies, such asMotorola,MOSTechnologies andZilogweresoonalsomakingmicroprocessors.IBM’s virtualmonopoly on computer systems soon started to slip asmany
companies developed computers based around the newly available 8-bitmicroprocessors, namely MOS Technologies 6502 and Zilog’s Z–80. IBM’smain contenders were Apple and Commodore who introduced a new type ofcomputer– thepersonalcomputer(PC).TheleadingsystemsweretheAppleIand theCommodore PET.These spawnedmany others, including the SinclairZX80/ZX81, theBBCmicrocomputer, the Sinclair Spectrum, theCommodoreVic–20andtheclassicAppleII(allofwhichwerebasedonoraroundthe6502orZ-80).IBMrealizedthepotentialofthemicroprocessorandusedIntel’s16-bit8086
microprocessor in their version of thePC. Itwas named the IBMPC and hassincebecometheparentofall thePCseverproduced.IBM’smainaimwas tomake a computer which could run business applications, such as wordprocessors, spread-sheets and databases. To increase the production of thissoftwaretheymadeinformationonthehardwarefreelyavailable.Thisresultedinmanysoftwarepackagesbeingdevelopedandhelpedclonemanufacturerstocopytheoriginaldesign.Sotheterm‘IBM-compatible’wasbornanditquicklybecameanindustrystandardbysheermarketdominance.On previous computers IBM had written most of their programs for their
systems.ForthePCtheyhadastricttimelimit,sotheywenttoasmallcomputercompany called Microsoft to develop the operating system program. Thisprogramwasnamed theDiskOperatingSystem (DOS)becauseof its originalpurposeofcontrollingthediskdrives.Itacceptedcommandsfromthekeyboardanddisplayed themto themonitor.The languageofDOSconsistedofasetofcommandswhichwere entereddirectly by the user and interpreted to performfilemanagement tasks,programexecutionandsystemconfiguration.Themainfunctions of DOS were to run programs, copy and remove files, createdirectories,movewithinadirectorystructureandtolistfiles.Microsoft has since gone on develop industry-standard software such as
MicrosoftWindows Version 3,Microsoft Office andMicrosoftWindows 95.Intel has also benefited greatly from the development of the PC and hasdevelopedalargemarketsharefortheirindustry-standardmicroprocessors,such
asthe80286,80386,80486,PentiumandPentiumProprocessors.
29.2IntroductiontoDOSMostmodernPCseitherrunDOSorallowaccesstoanemulatedversionofit.AllversionofMicrosoftWindowsupto,andincludingMicrosoftWindows3.1,required DOS to be running before Windows could run. Windows 95 andWindowsNTarecompleteoperatingsystemswithinthemselvesanddisplayanemulatedversionofDOS.
29.2.1CheckingTheVersionOfDOS(VER)ThefirstversionofDOSwasreleasedin1981andeachsubsequentreleasehasbeenassignedanewversionnumber.WhenthereisamajorchangeinDOSthenthe first number is changed, such as, Versions 1.0, 2.0, 3.0, and so on. Thesecondnumberchangeswitharelativelyminorchange,suchasversion1.1,1.2,1.3,andsoon.MostversionsofDOSarecompatiblewithpreviousversions.TodeterminetheversionofDOSthatacomputerisrunningthenentertheVER
command,asshowninTestrun29.1.ManycurrentsystemsuseVersion6orrunanemulatedDOSfromWindows95orWindowsNT.DOSversions later thanVersion4have anon-linehelpmanual.Todisplay
thehelppageonacommandthenHELPcommand_nameisentered,asshowninTestrun29.2.
29.2.2CheckingTheDateAndTime(DateAndTime)MostPCshaveanon-boardclockwhichispoweredbyarechargeablebattery.TheDATEcommanddisplaysthecurrentdateandallowstheusertochangethesystemdata,ifrequired.Testrun29.3showsanexample.Ifthedateisdisplayedcorrectlythenthe<ENTER>keyispressed,asshowninTestrun29.3.
IfthisdateisincorrectthenthecorrectdateisenteredattheEnternewdate(dd-mm-yy)prompt.Theexample inTest run29.4 shows that thecurrentdatehas been changed to Sunday 8/9/96. Care must be taken when entering thecurrentdateasthesystemmaybesetuptodisplaythedateinUSAformat,thatis,MM-DD-YY(MONTH,DAYandYEAR).TheTIMEcommanddisplaysthecurrenttime.Aswiththedatecommandthe
user ispromptedas towhether tochange thecurrent time,ornot.Pressing theENTERkeydoesnotchangethecurrenttime.Testrun29.6showsanexampleofchangingthesystemtimefrom10:55amto11:15pm.
29.2.3ClearingTheScreen(Cls)TheCLScommandclearsthescreenandleavesonlyapromptandthecursor.
29.2.4StartingAndStoppingDOSWhenthePCisrestarted,DOSisnormallystartedautomaticallyfromthehard-disk(unlessthesystemhasnohard-disks).SomePCstrytoreadthefloppydisksdrivesfor theDOSsystemfiles. If thishappensmakesure therearenofloppydisksinthedrives.ThemethodofstartingDOSisdescribedasthebootprocedure.Therearetwo
mainmethodsofstarting(orrestartingDOS):•Acoldboot–occursatpower-upandcausesthesystemtostartaself-test
program;•Awarmboot–isexecutedwhentheCtrl,AltandDelkeysarepresseddownsimultaneously(describedasCtrl-Alt-Del).Thisisnormallyrequiredwhenaprogramhascrashedandthesystemhashungup.
The Ctrl-Break keys (or Cntrl-C) are used to interrupt a DOS command.Testrun29.7showshowtheTIMEcommandisinterruptedusingtheCtrland‘Ckeys.
29.3DisksComputers store data on floppy disks, hard-disks and optical disks. The diskdrivesonaPCareidentifiedbythelabelsfromA:toZ:.Itisconventionthattheprimaryhard-diskdriveisdriveC:,theprimaryfloppydriveisA:,andthesecondaryfloppydriveisB:.,asgiveninTable29.1.
Table29.1Diskdriveallocation
DriveAllocation Description
A: Primaryfloppydiskdrive
B: Secondaryfloppydiskdrive
C: Primaryhard-diskdrive
D: Secondaryhard-diskdriveorCD-ROMdrive
Floppy and hard-disks store of information using magnetically fields onseparateconcentricrings–knownastracks.Thesearesubdividedintoblocksof512bits–knownassectors.Therearevariousdifferentformatsforthesetracksand sectors with varying capacities; these are given in Figure 29.2. Differingcapacitiesmayleadtocompatibilityproblems.
FIGURE29.2 Samplefilestructure
Table29.2Floppydiskcapacity
29.4Formattingfloppydisks(FORMAT)Theprimaryhard-diskisnamedC:andtheprimarydiskdriveisnamedA:.IfthePChasanotherfloppydiskdriveitisgiventhenameB:.Otherdrivescanexist,suchasfornetworkdrives,asecondaryhard-disk,aCD-ROMdrive,andsoon.Therearetwomaintypesoffloppydisks.Theseareusuallyreferredtobythe
disksdimensions,asshowninFigure29.2.OriginallyPCsusedthe5.25”floppydisks.Theyareextremelysensitivetophysicaldamage,especiallywhentheyarebent.Dataonthediskcanalsobecorruptedbyexternalparticlesorfingerprints.Thediskcanbeput intoadustcover–althoughitprovides littleprotectiontobeing bent. A better floppy disk uses a sliding metal shutter to protect themagnetic disk, this is the 3.5” disk. It also allows a greater amount of datastorage.A3.5”diskcanbeprotectedfromover-writingstoreddatabyslidingthewrite
protect button, as shown in Figure 29.2. There are two types 3.5” disk types,thesediffer in the amountofdata that canbe safely storedon them.Theyarenamedthedoubledensity(DD)andhighdensity(HD)disk.TheDDdiskhasamaximumcapacityof720KBandtheHDhas1.4MB.Normally,HDdisksaremore reliable thanDD disks, but they costmore to buy. AnHD disk can beidentifiedeitherbytheHDsymbolorbythenotchattheothersideofthewriteprotectslider.
FIGURE29.1 3.5”floppydisks.
29.4.1FormattingA3.5”DiskTheFORMATcommandsetsupthenecessaryformatonthedisksothatfilescanbestored.AsamplesessionisshowninTestrun29.8.
Notice that the message Saving UNFORMAT information is displayed. Thisallowstheusertounformatadiskthathasbeenformattedaccidentally(butonlyifnonewfileshavebeenwrittentothedisk).It is also possible to force the FORMAT command to format with a different
capacity.The/f switchextension isused for thispurpose.Table29.3outlineshowitismodifiedfordifferentcapacities.
Table29.3Floppydiskcapacity
Capacity Command Notes
720K formata:/f:720 DD3.5″floppydisk
1.44M formata:/f:1.44 HD3.5″floppydisk
360K formata:/f:360 DD51/4″floppydisk
1.2M formata:/f:1.2 HD51/4″floppydisk
29.5FilesystemstructureFiles storedata in the formofprograms,documents, spread-sheets, and soon.They are organized into a tree structure. The top of the structure is the rootdirectoryandeachbranchiscalledasubdirectory.Thisstructuremakesfindingfileseasierthanhavingallfilesstoredintheonedirectory.Theroutethroughthetreestructuretoagivenfileisknownasthepathname
and reference to files external to the current directory is possiblebyusing thecorrectpath.Thepathname foragiven file is traced through the tree structurefromtherootdirectorytothelocationofthefile.Test run 29.9 shows an example list of a top-level directory. The prompt
shouldbeset-uptodisplaythecurrentdirectory.Inthiscase,theDOSpromptisC:\>.The top level directory in this case contains various subdirectories such as
DOCS, WINDOWS, PSP and TURBO. Each of these directories contains files and/orsubdirectories. The function of each directory is normally obvious from itsname.Forexample,theDOSdirectorycontainsDOSprogram,helpmanualsandsystemfiles,theWINDOWSdirectorycontainsprogramsforMicrosoftWindows.
Thetop-leveldirectoryistherootdirectory,andisgiventhename\.Asmallsectionof thedirectoryhierarchy isgiven inFigure29.2.Notice that therearefour subdirectories below the root directory and that below theDOCS directorythere are three subdirectories NOTES, CLASSES and ADMIN. There is also onesubdirectory below WINDOWS. To identify the directories a pathname must begiven.Thefullpathnameeachdirectoryis:
AllthesedirectoriesarestoredontheharddiskwhichislabelledasC:,thusthefullpathname,withthediskdrive,ofthedirectoriesare:
Thesepathnamesarethefullpathnamesandareabsolutepathnames.Itisalsopossibletospecifyarelativepathname.Withrelativepathnamethenamegivendoesnothavetheprecedingtop-leveldirectory(\).Forexample,ifweareintheGAMESdirectorytherelativepathnamefortheDATAdirectoryisCHESS\DATAandifweareintheWINDOWSdirectorytherelativepathnamefortheSYSTEMdirectoryissimplySYSTEM.
29.6DOSFilenamesFilesarestoredondiskswithafilenameandanextension.Thefilenamecanbeuptoeightcharacterslongandtheextensionuptothreecharacters.Aperiod(‘.’) separates the filename from the extension. Figure 29.3 shows the standardformat.Theextensionnamegivesanindicationaboutwhattypeoffileitis.
FIGURE29.3 DOSfilenames
The valid characters that can be used for the filename are alphabeticcharacters (‘A’ – ‘Z’), numbers (‘0’ – ‘9’), underscores (‘_’), braces (‘{‘,’}’),parentheses (‘(7)’), tilde (‘~’), caret (’⁁‘), ampersand (‘&’), exclamation point(‘!’), pound sign (‘£’), hyphen (‘-’), and dollar sign (‘$’). Other specialcharacterssuchas(‘*’),(‘?’),(‘:’),(‘;’),(’,’),(‘=’),andsoon.arereservedforspecialfunctions.SomevalidandinvalidfilenamesaregiveninTable29.4.
Table29.4
ExamplesofvalidandinvalidDOSfilenames.
29.7FiletypesMostfilescreatedhaveacertainpurpose;forexampledocumentsfromawordprocessor, spread-sheets, text files. The filename extension adds extrainformationaboutwhattypeoffileitis.CommonfilenameextensionsaregiveninTable29.5.
Table29.5Examplefileextensions
Testrun29.10showsasampleDOSlisting.NoticethatthisdirectorycontainsSystemFiles (.SYS),DOSCommands (.COM and.EXE), Text Files (.TXT) andHelpFiles (.HLP).Theother typical files includeBasicLanguageFiles (.BAS),InitializationFiles(.INI)andListings(.LST).Programswiththe.COM,.EXEor.BATextensioncanbeexecuted.
29.8Listingfiles(DIR)TheDIRcommanddisplaysthecontentsofadirectory.AhelpmanualonDIRisgiveninTestrun29.11.Various switches modify the way the DIR command displays the directory
listing.RefertotheusermanualshowninTestrun29.11foracompletelisting.Testrun29.12showsasamplelistingwithoutswitches.
Table29.6ExampleswitchesfortheDIRcommand
Command Description
DIR/w displaydirectoryinfivecolumns
DIR/p displaysonescreenoflistingatatime
DIR/s displayallsubdirectoriesandfiles
DIR/od displaydirectoryinorderofdate
DIR/1 displaysdirectoriesinlowercase
Test run29.12showsanexamplesessionusingsomeof theformats.Noticethat thebasicDIR commanddisplaysnot only the filename and extension, butalsothefollowing:•Thevolumelabelofthedisk(inthiscase,THINKPAD).
•Thevolumeserialnumber,everydiskdrivehasauniquevolumeserialnumber(3A40–09E8).
•Thecurrentdirectoryname(C:\).•Thedirectorynameorfilename.•Thedatefileorsubdirectorywascreated,orwaslastmodified(forexample,
fortheDOSdirectoryitis05/01/95).•Thetimethefileordirectorywascreated,orwaslastmodified(forexample,
fortheDOSdirectoryitis12:00).•Thenumberoffilesinthedirectory(inthiscase,37).•Thediskspaceusedupbythefilesinthecurrentdirectory(inthiscase,65,
786bytes).•Theamountofavailablediskspace(inthiscase,41,353,216bytes).
The DIR/p displays one screen of directory information and the user ispromptedtoPressandkeytocontinue….Thiscontinuesuntilallthedirectoryinformation is displayed. The DIR/s command is useful for finding files insubdirectories. Several switches can be used at a single time, for example to
display all subdirectories with a pause between each screenful the commandusedisDIR/p/s.Worksheet 14: Note, if you are using Windows NT/95 then select either theMSDOS Prompt or shutdown Windows and select Restart the computer inMSDOSmode.W14.1.DeterminetheDOSversionofthePCyouareusing.
Version:
W14.2.DisplaythecurrentdateonthePC.
Date:
W14.3.DisplaythecurrenttimeofthePC.
Time:
W14.4.Modifythedateandtimeandredisplay.
Newdate:Newtime:
W14.5.Changethedateandtimebacksothattheyshowthecorrectdateand
time.
Completedsuccessfully: YES/NO
W14.6.UsetheCtrl-C(orCtrl-Break)keystrokestoquitfromtheTIMEcommand.
Completedsuccessfully: YES/NO
W14.7.Clearthescreen.
Completedsuccessfully: YES/NO
W14.8.Locatethefollowingkeys(tick,iffound):
Keys
FunctionskeysF1-F10 PageUp/PageDown
Altkey NumLock
Cntrlkey Home/End
CapsLock ESC
HorizontalTAB ScrollLock
Break Delete
W14.9.Displaythefollowingcharacterstothescreen(tick,iffound):
Keys √Keys √
£ \
< :
> (
? )
#
/ |
W14.10.ListallthefilesinthetopleveldirectoryontheC:drive.
Notesomeofcontents:FILES:DIRECTORIES:
W14.11.Whichofthefollowingarevalidnamesforfiles(tick):
Filename Valid(√) Invalid(√)
MY_FILE.DAT
DOC1,DOC
TEMP.$$$
WORK∼1.BAT
WORK??.BAT
TAX:1.DOC
$1.WP
W14.12.ForthefilestructuregiveninFigureW14.1completethetablegivennext(thefirstonehasbeencompleted):
FIGUREW14.1 Filestructure
Directory Fullpathname
ADMIN C:\DOCS\ADMIN
MEMO
BERT
BATCH
WINDOWS
SYSTEM
W14.13.ForthefilestructuregiveninFigureW14.2determinethefullpathnamesforthefilesgivennext(thefirstonehasbeencompleted):
FIGUREW14.2 Filestructure
FILE Fullpathname
T_SHEET.DOC C-\DOCS\ADMIN\T_SHEET.DOC
P_SHEET.DOC
MEMOI.DOC
XCOPY.EXE
MESSAGE.BAT
MOUSE.SYS
W14.14.UsingtheDIRcommandlistallthefilesontheharddisk(C:).UsetheCNTRL-Ckeystroketoexit.
Completedsuccessfully: YES/NO
W14.15.Whatistheprobablefunctionofthefollowingfiles:
File ProbableFunction
ADMIN.DOC DocumentFile
TAX91.WK1
DOSHELP.BAK
CONFIG.SYS
XCOPY.HLP
FIG1.PCX
GORILLA.BAS
HELP.TXT
W14.16.DeterminefromtheDIRlistingthesizeofthefollowingfilesontheharddisk:
FILE Sizeoffile(Bytes)
COMMAND.COM
CONFIG.SYS
AUTOEXEC.BAT
\DOS\XCOPY.EXE
\DOS\FC.EXE
W14.17.DeterminefromtheDIRlistingthedatethatthefollowingfileswere
lastmodified:
FILE Datelastmodified
COMMAND.COM
CONFIG.SYS
AUTOEXEC.BAT
\DOSkXCOPY.EXE
\DOS\FC.EXE
W14.18.Determinetheamountofdiskspacethatisremainingontheharddisk.
Diskspace:
W14.19.Determinetheamountofdiskspaceusedupbyallthefilesinthe\DOSdirectory:
DiskspaceusedbyDOSdirectory:W14.20.Determinethenumberoffilesinthe\DOSdirectory(orthe
\WINDOWSdirectoryifthereisno\DOSdirectory):DiskspaceusedbyDOSdirectory:
Numberoffiles:
W14.21.StatewhatthefollowingDIRcommandsdo(trythemout):
Command Function
dir/b Listsdirectoriesanddisplaysonlythenameofthefile/directory(barelisting)
dir/1
dir/on
dir/os
dir/od
W14.22.Rebootthecomputerusingawarm-boot.
Completedsuccessfully: YES/NO
W14.23.Rebootthecomputerusingacold-boot.
Completedsuccessfully: YES/NO
30
DOSFileSystem/Editor
30.1Changingdirectory(CDorCHDIR)
Thechangedirectorycommand,CD (orCHDIR)allows theuser tomovearoundthefilesystem.Table30.1showsafewsamplecommandsandSamplesession30.1showsasamplesession.Atthebeginningofthissessiontheuserisinthetopleveldirectory(C:\).TheDIR/Wcommandlistscontentsofthedirectoryacrossthe screen in five columns. In this case the main directory contains asubdirectorynamed\DOCS.TochangethecurrentdirectorytothisdirectorytheCDDOCScommandlineisused.Next,contentsofthisdirectoryarelistedusingDIR/W.
Table30.1ExamplesoftheCDcommand
Example Description
CD.. changedirectorytotheoneabovethecurrentdirectory
CD\ changedirectorytothetop-leveldirectory
CD\docs\notes\dos changedirectorytothedirectory\DOCS\NOTES\DOS
CDnotes changedirectorytothesubdirectoryNOTES
In the \DOCS directory there are nine subdirectories. Each of thesesubdirectorieshavetheirownfunction;forexample, lecturenotesarestoredintheNOTESdirectoryandgeneraladministrationdocumentsarestoredintheADMINdirectory.NotethatthefullpathnamefortheNOTESdirectoryisC:\DOCS\NOTES.Next,theuserchangesthecurrentworkingdirectorytotheDOCSdirectoryand
thentotheDOSsubdirectory.Thereareseveralfilesinthisdirectoryincludingthefiles DOS.DOC and DOS_S1.DOC. The full pathname of the file DOS.DOC isC:\DOS\DOCS\NOTES\DOS\DOS.DOC.
30.2Makingadirectory(MKDIRorMD)TheMKDIR (orMD)commandcreatessubdirectories.Samplesession30.2showsasamplesessionwherethesubdirectoryTEMPiscreatedinthetop-leveldirectory.
30.3Viewingafile(TYPE)The TYPE command views the contents of a file. A text file uses a standardalphabetknownasASCII.Non-ASCIIfilescontaindatawhichcannotbeviewedbytheuser.Samplesession30.3showsthelistingofthefileCONFIG.SYSwhichisinthetop-leveldirectory.NotethatthisfilecontainsinformationontheinitialstartupenvironmentofthePC.
30.4Wild-cards(*or?)Wild-cards are special characters which can be used to substitute variouscharactersinafilename.Therearetwowild-cardsusedinDOS,theseare:
*replacesanynumberofcharacters?replacesonlyonecharacterSamplesession30.4showsasamplesession.Theuserstarts inthetop-level
directoryandlistsallfilesordirectorieswhichstartwiththeletter‘d’(usingtheDIR d* command).Next the user changes the directory to \DOS.When in thisdirectory the user lists the files which have a SYS file extension (using DIR*.SYS).Next,all fileswhichbeginwith the letter ‘c’are listed(usingDIRC*).Finally,allfileswhichbeginwiththeletter‘m’haveanysecondletterfollowedbytheletters‘av’andwithanyfileextensionarelisted(usingDIRm?av.*).
30.5CreatingatextfileDOS Version 5.0/6.0 andWindows 96 have a text editor named EDIT. Thiseditor isuseful tocreate text filesbutcannotbeusedwith softwareprograms.For this reason an integrated development environment (IDE) editor will beused..TheexampleusedinthissectionisBorlandC++Version3.0,asshowninFigure30.1.
FIGURE30.1 BorlandC++Version4.0mainscreen.
Many networks allows access to the compiler through a menu option. Oncomputerswherethecompilerisinstalledonthelocalharddisk,thentypicalset-
upsaregiveninTable30.1.FortheBorlandproducts(TurboPascal/BorlandC/TurboC)afileisentered
bysimplyenteringtextintotheeditwindow.ThemainmenuoptionsareFile,Edit, Run, Compile, Options, Debug. Once the file text has been enteredthenitissavedbyusingtheFile→Saveoption.AsadefaultCfilesaregiveaCextension, C++ are given a CPP extension, and Pascal files are automaticallyassignedaPASextension.ToloadapreviouslysavedfiletheFile→Openoptionisused.
Table30.2IDEpackages
IDE Programtorun Typicalhomedirectory
BorlandC++Version4 BC.EXE C:\BORLAND\BIN
TurboCVersion2 TC.EXE C:\TC
TurboPascal TURBO.EXE C:\TURBO
30.8DeletingFiles(DELorERASE)The DEL and ERASE commands delete files. Wild-cards can be used to replacefilenames, if required. Sample session 30.5 shows a sample sessionwhere thefile TEST3.TXT is deleted from the TEMP directory. Next, all the files with a TXTextensionaredeleted.As an extra safeguard against accidentally deleting, or selectively deleting
files the /P switch can be used. Notice in Sample session 30.6 the user ispromptedtodeleteeachofthefilesindividually.
30.9Copyingfiles(COPY)TheCOPYcommandisusedtocopyfiles.TheformatoftheCOPYcommandisgivennext:
whereSOURCEisthenameofthefiletocopyandDESTINATIONisthenameofthefile,ordirectory,tocopyto.InSamplesession30.7theusercreatesadirectorynamedTEMP.Next,theuser
changesthedirectorytotheTEMPsubdirectory.Notethatthisdirectoryisempty.A file namedTEST1.TXT is created using theDOS editor (EDIT).After this it islistedusingtheTYPETEST1.TXTcommandline.Next the directory is listed using DIR and then the COPY command is used to
copy thenewcreated file toTEST2.TXT.Adirectory listing(DIR) then showsthattherearenowtwofilesinthisdirectory(TEST1.TXTandTEST2.TXT).Next,thefirstfile(TEST1.TXT)isdeletedusingERASEcommand.
Worksheet15:W15.1.Gotothetop-leveldirectory,thenmovearoundthefilesystemlooking
invariousdirectories.Trytodeterminethelikelyfunctionofthedirectories.
Directory Likelyfunction
C-\DOS DOSdirectorycontainingsomeDOScommands,helpfunctions,systemfiles,andsoon
W15.2.FindallthefileswhichhavetheDOCextensionontheharddisk(hint.usetheDIR/Scommand).
File(*.DOC) Directory
DOS.Doe C:\NOTES\DOeS\DOS
FindallthefilesontheharddiskwiththeBATextension.
File(*.BAT) Directory
AUTOEXEC.BAT C:\
W15.3.CreateadirectorynamedTEMPontheharddisk.
Commandused:
W15.4.Gointothedirectoryyouhavejustcreated.
Commandused:
W15.5.CreateafilenamePROG1.C(ifyouindenttouseC)orPROG1PAS(ifyouindendtousePascal)fromtheIDEeditor,enterthefollowingtextandsavethefile.
W15.6.CheckthatthefilejustcreatedexistsusingtheDIRcommandDoesitexist:YES/NOW15.7.ViewthecontentsofthisfileusingTYPE.
Arethecontentscorrect:Yes/NO
W15.8.CopythisfileintoafilenamedPROG2.C(orPROG2.PASifthefilecreatedisPROG1.PAS)usingtheCOPYcommand.
Commandused:
W15.9.VerifythattheCOPYcommandhasworkedbylistingthedirectory.
Hasthefilebeencopiedcorrectly:YES/NO
W15.10.ViewthecontentsofthenewlycreatedfileusingTYPE.
Arethecontentscorrect:YES/NO
W15.11.Insertadiskintooneofthediskdrivesandformatafloppydisk(ifyouhaveone).
Commandused:YES/NO
W15.12.GotothefloppydiskandcopythefilePROG1.C(orPROG1.PAS)fromtheC:\TEMPdirectoryandconfirmthatithascopiedcorrectly.
Commandused:
W15.13.DeterminetheVolumelabeloftheharddiskyouareusing.
Volumelabel:
W15.14.DeterminethenamesthatDOSwilluseforthefollowingfiles/directories:
Filename DOSfilenameactuallygiven
MYFILE421.TEXT MYFILE.TEX
DOC$1001.D
ACC9192.WK1
BACKUP.$$11
DOCS.FRED.1
MEMOFRED.200
W15.15.Copythefollowingfilesthatshouldbeinthetop-leveldirectoryontheharddisk.
Copyfrom Copyto
AUTOEXEC.BAT AUTOEXEC.OLD
CONFIG.SYS CONFIG.OLD
Filescopiedokay:YES/NO
W15.16.MakeadirectorynamedOLDBATSandcopythefilesCONFIG.OLDandAUTOEXEC.OLDintothisdirectory.
Filescopiedokay:YES/NO
31
Introduction
31.1Introduction
AmodernPersonalComputer(PC)consistsofakeyboard,amonitor,amouse,afloppy disk drive, a hard disk drive and a system unit. An operating systemallowstheusertoaccessthesedevicesinaneasy-to-usemanner,asillustratedinFigure31.1.MicrosoftDOS(DiskOperatingSystem)isatext-basedsysteminwhich commands are entered via the keyboard to perform operations such ascopyingfilesandrunningprograms.
FIGURE31.1 Usinganoperatingsystemtoaccesshardware
Microsoft Windows is a program which presents an easy-to-use graphicalinterface to the PC hardware. It uses windows, icons, menus and pointers(WIMPs) to access application programs, disk drives, file systems, and so on.Most operations are conductedusing amouse insteadof keyboard commands.The user is presented with a series of icons which represent applicationprograms. It is far simpler to use than DOS as the information is presentedgraphically.AmajordisadvantageofDOSis that thesyntaxandformatof thetextcommandrequirestoberemembered.
Windows has gone through three major transformations, from the originalVersion 1.0 to themostwidely available version toVersion 3.1 (andVersion3.11)andnowtoWindows95/NT.It isinstalledonalmosteverynewPCsoldand is becoming the de-facto standard for PC packages. This and the nextchapterdiscussWindows3.1/3.11.
31.2RunningWindowsWindows 3.x is a program which is run from DOS. It will either startautomaticallywhenthePCisswitchedon,orcanberunbytypingWINattheDOSpromptandpressing<RETURN>.
31.3WindowsdesktopAfterWindowsisstartedthescreendisplaystheMicrosoftstart-upscreenforashorttime.Thisdisplaystheversionnumberofthesoftware.ThemainWindowsdesktop is displayed after this. On top of the desk is the Program Managerwindow. It contains a number of windows and icons within it. Programs andapplicationsareplacedintogroups.Thesegroupscontainiconswhichrelatetotheprogram.Theinactivewindowsaredisplayedasgroupicons.Therearefourofthese,asshowninFigure31.2.Awindowismadeactivebydoubleclickingonthegroupicon.Thisexpandsthewindowtoitsnormalform.
FIGURE31.2 Maindesktopscreen
Aprogramwhichhasbeenrunningbutiscurrentlypausedisshownasaniconat the bottom of the screen. In the example screen in Figure 31.3 there are 4activegroups,theseare:Accessories,Main,MsofficeandApplications.WithintheAccessories group there are 12 programs, these are: Write, Paintbrush,Terminal, Notepad, Recorder, Cardfile, Calculator, Clock, Object
Packager,CharacterMapper,MediaPlayerandSoundRecorder.
FIGURE31.3 Abasicgroupwindow
Thecurrentactivewindowhasabluetitlebarswhilstaninactivewindowhasagreytitlebar.Onlyiconswithinanactivewindowcanbeselected.
31.4WindowitemsWindowsaremadeuptofourmainparts,theseare:•Maintitlebar.Everywindowhasanidentificationtitleatthetopofit,as
showninFigure31.3.•Menubar.Somewindowshavemenuoptionstochoosefrom,asshownin
Figure31.4.Hot-keysareoftenunderlined.
FIGURE31.4 Menubaronawindow
•Scrollbar.Whenonlypartofawindowisdisplayedascrollbar(oftencalledathumbnail)willappear.Holdingdownthemousebuttononthesmallsquarewithinthescrollbarmovesthecontentsofthewindow.
•Controlmenubox.AsshowninFigure31.3.
31.5MousecontrolsThemousecontrols thepointeraround the screenand the leftmousebutton isused either to run an application, if it is an icon, or to single click to select awindoworfile,asshowninFigure31.5.
FIGURE31.5 Maindesktopscreen
31.6ProgramManagermenusTheProgramManagerwindowhas4menuoptions:File,Options,WindowsandHelp.Table31.1 shows themainoptions and the sub-options.For example, ifthe File menu options is selected a sub-menu (a pull-down menu) shows theoptions:,New,Open,Move,Copy,Delete,Properties,RunandExitWindows.
Table31.1Menuoptions
31.6.1QuittingWindowsToexitWindows,firsttheFileoptionisselectedfromProgramManager.Next,movethemousepointerdownto theExitWindowsoptionandselect itwithasingleclickoftheleftmousebutton,asshowninFigure31.6.
FIGURE31.6 QuittingWindows
31.6.2GettingHelpThe best method of getting help is to refer to the user manual. If that is notavailable then there ison-linehelp. If theHelpmenuoption is selectedon theProgramManagermenudisplaystheoptionsContents,SearchforHelpon,HowtouseHelp,WindowsTutorialandAboutProgramManager.
31.7MovingandresizingawindowTheoptionsusedtochangethewindowssizeare:•Maximizingawindow.Awindowcanbemadetofillthecompletescreenby
selectingthe atthetopright-handcornerofthescreen.•Minimizingawindow.Awindowcanbeminimizedtoaniconusing•Makingawindowsmaller.Ifawindowisfillingthecompletescreenitcan
bemadeintoasmallerwindowbyselecting•Movingawindow.Awindowcanbemovedbyplacingthemousepointeron
thebluetitlebar.Theleftmousebuttonispresseddownwhilemovingthewindowtoitsrequiredposition,thenthemousebuttonisreleased.
•Resizingawindow.Awindowcanberesizedbyplacingthemousepointereitheratoneofthecornersorthesides.Thepointershapeshouldchangewhenitisplacedovertheborderofthewindows.Toexpand(orcontract)thewindowverticallythemousepointerisplacedeitheratthetopor
bottomborder.Themouseisthenpressedwhilemovingtheborderofthewindows.Whentherequiredpositionisfoundthemousebuttonisreleased.Asimilaroperationcanbeconductedtoexpand(orcontact)horizontally.
31.8ClosingawindowwiththeControlmenuThe Control menu is activated by selecting the top left-hand button on thewindow. This menu contains the options: Restore, Move, Size, Minimize,Maximize,Close,Switchto.TheRestore,Move,Size,MinimizeandMaximizeoptionsmimicoperationsthatareconductedbythemouse.AusefuloptionistheClosewhichexitsfromthewindowandclosesitdown,thisisshowninFigure31.7.
FIGURE31.7 Controlmenu
31.9ExercisesConductthefollowingstepsfillingintherequiredinformation.31.9.1.SwitchPCon.Completedsuccessfully[]31.9.2.StartMicrosoftWindowsandwhenitshowstheinitialstart-upscreen
observetheversionnumberofthesoftware.
31.9.3.IdentifyeachoftheactiveandinactivegroupswithintheProgram
Manager.
31.9.4.Identifyallprogramswithinthreeofthegroups.
31.9.5.ResizetheProgramManagerwindowsothatitfillsthescreen.Tickboxifcompletedsuccessfully.
Completedsuccessfully[]31.9.6.ResizetheProgramManagerwindowsothatitisshownatitsnormal
positiononthescreen.Completedsuccessfully[]
31.9.7.IconizetheProgramManagerwindowandthenrestoreittoitsnormalposition.
Completedsuccessfully[]31.9.8.ExpandtheProgramManagerwindowhorizontally,thenrestoreittoits
normalposition.Completedsuccessfully[]31.9.9.ContracttheProgramManagerwindowsvertically,thenrestoreittoits
normalposition.Completedsuccessfully[]31.9.10.Findthefollowingapplicationprograms,runthemandthenexit.Tick
boxifcompletedsuccessfully.
31.9.11.ExitfromWindowsusingtheFilemenuoptionintheProgramManager.
31.9.12.StartWindowsagainandthistimeexitusingtheControlmenu.Operationsused:
31.9.13.Thereisanon-linehelpfacilitywithinWindows.ToselectthisusetheHelpmenuoptionwithintheProgramManager.Usethisfacilitytofindhelponthefollowingtopics.
quittingwindows:—————————deletinggroups:—————————startingapplications:—————————deletingprograms:—————————
32
FileManagement
32.1Introduction
TheMain groupcontains important applicationprogramswhich allow theuseraccess to the file system, to setup a different environment, to setup differentcomputerhardware,gainaccesstoDOS,etc.ItcontainsControlPanel,PrintManager, File Manager, ClipBook Viewer, MS-DOS Prompt, Windows
Setup,PIFEditorandSysedit.TheiconscontainedwithinMainareshowninFigure32.1.
FIGURE32.1 Maingroup
ControlPanelsetsuptheWindowsenvironmentandcanbeusedtochangethe colours of the windows, the fonts used, etc. The Print Manager programchecksthestatusoffileswhichhavebeenprinted.FileManagerallowsaccesstothe file system and can be used to copy or move files from one directory toanotherorfromonediskdrivetoanother.TheMS-DOSPromptprogramgivesaDOSwindow.
32.2FilemanagerThefilemanagerisidentifiedbythefilingcabineticon.Itisopenedbydouble
clickingthecabineticon.Filesanddirectoriesaredisplayedwiththeirfilenameand an icon which indicates the file type. It employs a select, drag and puttechniquewhereafile(ordirectory),onceselected,canbedraggedintoanotherdirectory or onto any disk drive.Note that the filemanager inWindows 3.11differs slightly from the filemanager inWindows 3.1. Figure 32.2 shows theWindows3,11filemanager.Themaindifferenceistheiconstotherightofthecurrentdiskdrivename.
FIGURE32.2 Filemanager
A directory is identified with the icon. Files have three main iconsassociatedwiththem.Applicationprogramsareidentifiedwitha adocumentfile by and any other filewith a . Figure 32.3 shows a sample directorylisting.
FIGURE32.3 Filemanager
Adocumentfile isa filewhichwhendoubleclickedwillstartanassociatedapplication.Table 32.1 shows some typical file extensions and the applicationwhich is run when the file is double clicked. For example, a file with a docextensionwill run awordprocessor, abmpextensionwill start thepaintbrushpackage,andsoon.
Table32.1Fileassociatedwithapplication
Fileextension Description Applicationstarted
wav Soundfile Soundpackage
txt Textfile Notepad
doc Document Wordprocessor
wk3 Lotus123worksheet Lotus123
wri Writedocument Write
hlp Helpfile Windowshelp
pcx Graphicsfile Paintbrush
xls MicrosoftExcellworksheet MicrosoftExcell
ppt MicrosoftPowerpointpresentation MicrosoftPowerpoint
bmp Bit-mappedgraphicsfile Paintbrush
32.2.1SelectingADriveAdiskdrive is selectedwitha singleclickononeof thedisk iconsabove thedirectorylistingorbyselectingDisk→Selectdrive….IntheexampleinFigure32.4therearethreedrives,afloppydiskontheA:drive,ahard-diskontheC:driveandaCD-ROMontheD:drive.Ifthereareanynetworkdrivesthesewillalsobedisplayed.
FIGURE32.4 Displayingdirectory
32.2.2SelectingADirectoryAdirectoryisselectedbyasingleclickonthedirectoryicon(oronthedirectoryname).Theopen file icon ( ) then showswhichdirectory is currentlyopen;thedirectorydisplaywindowdisplaysthecontentsofthisdirectory.Anexampleof changing the currentdirectory is shown inFigure32.5. In this example theuserhas selected to list thecontentsof the top-leveldirectoryon theC:drive.Next themousepointer isplacedover thedocsdirectorywhichis thenopenedwith a single click of the leftmouse button.After this the admin directory isopened.Adirectorycanbeclosedbysinglemousebuttonclickwhenitisopen
(anotherclickwillopenitagain).
FIGURE32.5 Selectingdiskformatoption
32.2.3FormattingADiskAfloppydiskmustbe formattedbefore it can store files.Somedisks arepre-formattedwhen theyarepurchased,butothers required tobe formattedbeforetheyareused.Caremustbetakenwhenformattingadiskasthecurrentcontentsofthediskwillbeerased.To format a disk first insert it into the floppy disk drive. Next select
Disk→Format disk … from themenu, as shown in Figure 32.5.When this isselectedWindowswill prompt the user for the drivewhich the disk has beenenteredandthecapacityofthedisk.BydefaultthisislikelytobesettoA:and1.44MB(fora3.5 inchfloppydiskdriveontheA:drive),respectively.If thedrive differs from the default or its format differs then change the options bypullingdowntheDiskInortheCapacityoptions.Figure32.6shows themainsteps thatare taken to format thedisk.First the
diskcapacityanddrivenamearepromptedfor.WhenthesearecorrecttheOKbutton is selected. Next a Format Disk window is displayed. Within thiswindowthecurrentstatusofthediskformattingoperationisdisplayed(from0to100%complete).Whencomplete,awindowwithamessageCreatingrootdirectory will be displayed. After this the formatted disks’ capacity isdisplayedandtheuserispromptedastowhetheranotherdiskistobeformatted.Ifnomoredisks are tobe formatted then theNo option is selectedelseYes isselected.NotethattheCanceloptiononanyoftheformatstatuswindowscanbeselectedtocanceltheformatprocess.
FIGURE32.6 Formattingafloppydisk
32.2.4MovingFilesOnTheSameDiskDriveMicrosoftWindows uses a select, drag and drop procedure when copying ormovingfilesordirectories.Movingfiles(copyingthembutdeletingtheoriginalfile) can be achieved by moving the mouse pointer over the file and thendraggingtheicon,whilekeepingtheleftmousebuttonhelddown,thenplacingit in thedesireddirectory.Figure32.7 showsan exampleof the file acc2.wk1beingdraggedintothedirectoryC:\DOCS\BUSINESS.
FIGURE32.7 Copyingormovingafileonthesamediskdrive
32.2.5CopyingFilesOnTheSameDiskDriveCopying files toanew location is achievedbyholdingdown theCtrlkeyanddraggingthefiletothedesireddirectory,seeFigure32.8.
FIGURE32.8 Deleteconfirmation
32.2.6CopyingFilesToADifferentDiskDriveCopying filesordirectories toadiskdrive isachievedbysimplydragging thefile or directory icon to the drive icon. This is similar tomoving files on the
same disk drive but in this case the file will not be deleted on the sourcedirectory.
32.2.7MovingFilesToADifferentDiskDriveMovingfilesordirectoriestoanotherdiskdriveisachievedbysimplydraggingthe file or directory icon, while pressing the Shift key, and dragged it to therequireddriveicon.
32.2.8DeletingFilesWhenafileisnolongerrequireditcanbedeleted.Thisisachievedbyclickingonthefile tobedeletedandpressingtheDelkeyonthekeyboard.Amessageaskingforconfirmationshouldappear,asshowninFigure32.8.IfthefileistobedeletedthentheOKbuttonisselectedelseCancel.Theconfirmationwindowfordeletingadirectory isdifferent,anexample is shown inFigure32.9.AftertheuserselectsthedirectorytodeleteaconfirmationisdisplayedwitheitherYesorYes toAll.IftheuserselectsYes theneachfilewithinthedirectorywillbepromptedfordeletionconfirmation.IfYestoAllisselectedthenallfileswithinthedirectory(andsub-directories)willbedeletedwithoutanyconfirmation.
FIGURE32.9 Deletedirectoryconfirmation
32.2.9RunningWindowsAndDOSApplicationsRunningafileisachievedbyplacingthemousepointerovertheapplicationfileand double clicking the left mouse button. If it is a Microsoft Windowsapplication it will be run as a normalWindows application, else if it has anapplication attached to it then the associated application will be run and theselectedfileloadedintoit.Forexample,ifitwereadocumentfile(.DOC)thena
wordprocessorwillbestartedwiththeselecteddocumentloadingintoit.IfaDOS-basedapplicationisselectedthenaDOSscreenwillappearwhich
willthenloadtheprogram(ifitcan).
32.3ExercisesConductthefollowingstepsfillingintherequiredinformation.32.3.1.StartMicrosoftWindows.Completedsuccessfully[]32.3.2.Identifysomeofthedirectoriesandsub-directoriesontheC:driveonthe
PCandcompletethetablegiveninFigure32.10.
FIGURE32.10 DirectorystructureofC:drive
32.3.3.Identifysomeapplicationprogramswithinthe\dosdirectory.Applicationprograms:________________________________________
32.3.4.Identifysomeapplicationprogramswithinthe\windowsdirectory.Applicationprograms:________________________________________32.3.5.Identifysomefileswhichareinthe\WINDOWSdirectorywhichwillrun
applicationprogramsFiles:________________________________________32.3.6.OntheC:drivefind5graphicsfiles(inanydirectory).Files:Files:________________________________________32.3.7.OntheC:drivefind5documentfiles(inanydirectory).Files:Files:________________________________________32.3.8.InsertafloppydiskintheA:driveandformatit.Totaldiskspace:________________________________________32.3.9.CreateadocumentfileeitherbyrunningCardfile(withintheMain
group)orrunningWrite(withinAccessories)orusingawordprocessorsuchasWordforWindowsorAmi-Pro.EntersometextintothedocumentthensaveitintheC:\windowsdirectorywiththenameDOC1.DOC.
Completedsuccessfully[]32.3.10.Verify,withFileManager,thatthisfileisinthe\windowsdirectory.Completedsuccessfully[]32.3.11.CopythefileDOC1.DOCtothefloppydiskintheA:drive.Completedsuccessfully[]32.3.12.Verify,withFileManager,thatthefilehasbeencopiedtotheA:drive.
Ifitisinthewrongplacemoveit.Completedsuccessfully[]32.3.13.CreateadirectoryontheC:drive,namedtemp,belowthetop-level
directoryusingtheFile→CreateDirectorymenuoption.Completedsuccessfully[]32.3.14.Verify,withFileManager,thatthisdirectoryexists.Ifitisinthewrong
placemoveit.Completedsuccessfully[]32.3.15.CopythefileDOC1.DOCtothetempdirectory.Completedsuccessfully[]
32.3.16.Verify,withFileManager,thatthefileisinthetempdirectory.Completedsuccessfully[]32.3.17.Thereisanon-linehelpfacilityforthehelpmanagerwithinWindows.
ToselectthisusetheHelpmenuoptionwithintheFileManager.Usethisfacilitytofindhelponthefollowingtopics.
selectingfiles:———————–sortingfiles:———————–copyingdisks:———————–startingapplications:———————–
33
Windows95/NT
33.1Introduction
Windows NT has provided an excellent network operating system. Itcommunicates directly with many different types of networks, protocols andcomputerarchitectures.WindowsNTandWindows95havethegreatadvantageof other operating systems in that they have integrated network support.Operatingsystemsnowusenetworkstomakepeer-to-peerconnectionsandalsoconnections to servers for access to file systems and print servers. The threemost widely used operating systems are MS-DOS, Microsoft Windows andUNIX. Microsoft Windows comes in many flavours; the main versions areoutlinedbelowandTable33.1listssomeoftheirattributes.
Table33.1Windowscomparisons
•MicrosoftWindows3.xx–16-bitPC-basedoperatingsystemwithlimitedmultitasking.ItrunsfromMS-DOSandthusstillusesMS-DOSfunctionalityandfilesystemstructure.
•MicrosoftWindows95–robust32-bitmultitaskingoperatingsystem
(althoughtherearesome16-bitpartsinit)whichcanrunMS-DOSapplications,MicrosoftWindows3.xxapplicationsand32-bitapplications.
•MicrosoftWindowsNT–robust32-bitmultitaskingoperatingsystemwithintegratednetworking.NetworksarebuiltwithNTserversandclients.AswithMicrosoftWindows95itcanrunMS-DOS,MicrosoftWindows3.xapplicationsand32-bitapplications.
33.2Servers,workstationsandclientsMicrosoftWindowsNTisa32-bit,pre-emptive,multitaskingoperatingsystem.One of the major advantages it has over UNIX is that it can run PC-basedsoftware.AWindowsNTnetworknormallyconsistsofaserverandanumberofclients.Theserverprovidesfileandprintserversaswellaspowerfulnetworkingapplications, such as electronic mail applications, access to local and remoteperipherals,andsoon.TheWindowsNTclientcaneither:•Operateasastand-aloneoperatingsystem.•Connectwithapeer-to-peerconnection.•ConnecttoaWindowsNTserver.Apeer-to-peerconnectioniswhenonecomputerlogsintoanothercomputer.
Windows NT provides unlimited outbound peer-to-peer connections andtypicallyupto10simultaneousinboundconnections.
33.3WorkgroupsanddomainsWindowsNTassignsuserstoworkgroupswhicharecollectionsofuserswhoaregrouped together with a common purpose. This purpose might be to shareresources such as file systems or printers, and each workgroup has its ownuniquename.WithworkgroupseachWindowsNTworkstationinteractswithacommon group of computers on a peer-to-peer level. Each workstation thenmanagesitsownresourcesanduseraccounts.Workgroupsareusefulforsmallgroups where a small number of users require to access resources on othercomputers.A domain in Windows NT is a logical collection of computers sharing a
common user accounts database and security policy. Thus each domain musthaveatleastoneWindowsNTserver.
Windows NT is designed to operate with either workgroups or domains.Figure33.1illustratesthedifferencebetweendomainsandworkgroups.
FIGURE33.1 Workgroupsanddomains
Domainshavetheadvantagesthat:•Eachdomainformsasingleadministrativeunitwithsharedsecurityanduser
accountinformation.Thisdomainhasonedatabasecontaininguserandgroupinformationandsecuritypolicysettings.
•Theysegmenttheresourcesofthenetworksothatusers,bydefault,canviewallnetworksforaparticulardomain.
Useraccountsareautomaticallyvalidatedbythedomaincontroller.Thisstopsinvalidusersfromgainingaccesstonetworkresources.
33.4WindowsNTuserandgroupaccountsEachuserwithin a domainhas a user account and is assigned to oneormoregroups.Eachgroupisgrantedpermissionsforthefilesystem,accessingprinters,andsoon.Groupaccountsareusefulbecausetheysimplifyanorganizationintoa single administrative unit. They also provide a convenient method ofcontrollingaccessforseveraluserswhowillbeusingWindowsNTtoperformsimilartasks.Byplacingmultipleusersinagroup,theadministratorcanassignrightsand/orpermissionstothegroup.
EachuseronaWindowsNTsystemhasthefollowing:•Ausername(suchasfred_bloggs).•Apassword(assignedbytheadministratorthenchangedbytheuser).•Thegroupsinwhichtheuseraccountisamember(suchas,staff).•Anyuserrightsforusingtheassignedcomputer.Each time a user attempts to perform a particular action on a computer,
Windows NT checks the user account to determine whether the user has theauthoritytoperformthataction(suchasreadthefile,writetothefile,deletethefile,andsoon).Normallytherearethreemaindefaultuseraccounts:Administrator,Guestand
an‘InitialUser’account.ThesystemmanagerusestheAdministratoraccounttoperformsuchtasksasinstallingsoftware,adding/deletinguseraccounts,settingupnetworkperipherals,installinghardware,andsoon.Guestaccountsallowoccasionaluserstologonandbegrantedlimitedrights
onthelocalcomputer.Thesystemmanagermustbesurethat theaccessrightsarelimitedsothathackersorinexperienceduserscannotdodamagetothelocalsystem.The ‘InitialUser’ account is createdduring installationof theWindowsNT
workstation.Thisaccount,assignedanameduring installation, isamemberoftheAdministrator’s group and therefore has all theAdministrator’s rights andprivileges.After the systemhas been installed theAdministrator can allocate newuser
accounts,eitherbycreatingnewuseraccounts,orbycopyingexistingaccounts.
33.5FilesystemsWindowsNTsupportsthreedifferenttypesoffilesystem:•FAT(fileallocationtable)–asusedbyMS-DOS,OS/2andWindowsNT/95.
Asinglevolumecanbeupto2GB.•HPFS(highperformancefilesystem)–aUNIX-stylefilesystemwhichis
usedbyOS/2andWindowsNT.Asinglevolumecanbeupto8GB.MS-DOSapplicationscannotaccessfiles.
•NTFS(NTfilesystem)–asusedbyWindowsNT.Asinglevolumecanbeupto8GB.MS-DOSapplications,themselves,cannotaccessthefilesystembuttheycanwhenrunwithWindowsNT.
TheFATfilesystemiswidelyusedandsupportedbyavarietyofoperatingsystems, suchasMS-DOS,WindowsNTandOS/2. If a system is touseMS-
DOSitmustbeinstalledwithaFATfilesystem.
33.5.1FATThe standardMS-DOS FAT file and directory-naming structure allows an 8-character file name and a 3-character file extension with a dot separator (.)betweenthem(the8.3filename).Itisnotcasesensitiveandthefilenameandextensioncannotcontainspacesandotherreservedcharacters,suchas:
WithWindowsNTandWindows95 theFATfile systemsupports long filenameswhichcanbeup to255characters.Thenamecanalsocontainmultiplespacesanddotseparators.Filenamesarenotcasesensitive,butthecaseoffilenames is preserved (a file named FredDocument.XYz will be displayed asFredDocument.XYz but canbe accessedwith anyof the characters in upper orlowercase).Each file in the FAT table has four attributes (or properties): read-only,
archive,systemandhidden(asshowninFigure33.2).TheFATusesalinkedlistwhere thefile’sdirectoryentrycontains itsbeginningFATentrynumber.ThisFATentryinturncontainsthelocationofthenextclusterifthefileislargerthanonecluster,oramarkerthatdesignatesthisisincludedinthelastcluster.Afilewhichoccupies12clusterswillhave11FATentriesand10FATlinks.
FIGURE33.2 Fileattributes
ThemaindisadvantagewithFATisthatthediskissegmentedintoallocatedunits (orclusters).On large-capacitydisks thesesectorscanbe relatively large(typically512bytes/sector).Diskswithacapacityofbetween256MBand512MBuse16 sectorsper cluster (8KB)anddisks from512MB to1GBuse32sectors per cluster (16KB).Drives up to 2GBuse 64 sectors per cluster (32KB).Thusifthediskhasacapacityof512MBtheneachclusterwillbe8KB.Afilewhichisonly1KBwillthustakeup8KBofdiskspace(awastageof7KB),anda9KBfilewilltakeup16KB(awastageof7KB).Thusafilesystemwhich has many small files will be inefficient on a cluster-based system. Afloppydisknormallyuse1clusterpersector(512bytes).Windows 95 andWindowsNT support up to 255 characters in file names;
unfortunately,MS-DOS andWindows 3.xx applications cannot read them. Toaccommodatethis,everylongfilenamehasanautogeneratedshortfilename(inthe form XXXXXXXX.YYY). Table 33.2 shows three examples. Theconversiontakesthefirstsixcharactersofthelongnamethenaddsa~numbertothenametogiveitauniquename.Filenameswiththesameinitialsixcharactersareidentifiedwithdifferentnumbers.Forexample,ProgramFilesandProgramDirectory would be stored as PROGRA~1 and PROGRA~2, respectively. Samplelisting33.1showsalistingfromWindowsNT.Theleft-handcolumnshowstheshortfilenameandthefarright-handcolumnshowsthelongfilename.
Table33.2
Filenameconversions
Longfilename Shortfilename
ProgramFiles PROGRA∼1
Triangular.bmp TRAING∼1.BMP
Fredte∼1.1 FRED.TEXT.1
33.6RunningWindows95andNTWindows95andNTareoperating systems in theirown right and thusdonotrequireDOS.TheversionofDOSwhichisruninWindow95/NTisanemulatedversion.SometimesWindowsNT/95developsaproblemwhenstartingthecomputer.
Ifthisoccursthenitcanbestartedinasafemode,whichdoesnotloadnetworksupport and using the default settings (VGA monitor, no network, Microsoftmousedriver,andtheminimumdevicedriversrequiredtostartWindows).ThisisachievedbypressingtheF8keywhenWindowsisbeingbooted.Normallytheuser then selects Settings and then Control Panel to change the systemssettings.Oftentheproblemwiththesystemstart-upistodowitheitherAUTOEXEC.BAT
or CONFIG.SYS files. If this is the case the Command Prompt Only operationsettingcanbeselectedwhenstartingthecomputer.Thisoptionbypassesthetwosystemfiles.Otherwise,theStep-by-StepConfirmationcanbeselected,whichallowstheusertoloadaspecificsystemdriver.Anothermethod of fixing the system is to boot the systemwith a bootable
DOSdisk.Theuser can then try to fix the system.Note that this canonly bedoneifthediskhasbeenformattedasFAT.
33.7BasicWindowsNT/95There are many enhancements on Windows NT/95 as opposed to previousversions.Themaindifferencesare:
• Startbuttonandtaskbar.ThetaskbarappearsatthebottomofthescreenanditcontainstheStartbutton,whichcanbeusedtoquicklystartaprogram.Thetaskbaralsoshowstheprogramswhicharecurrentlyrunninganditcanthusbeusedtoswitchbetweenprograms.
• Folders.Documentsandprogramsarestoredinfolders.InDOSandpreviousversionsofWindowsthesefolderswerecalleddirectories.
•Thedesktop.ThedesktopistheareaofscreenwhichappearswhenWindowsisstarted.Figure33.3showsanexample.Itcanbecustomizedbyaddingprogramshortcuts,documents,printers,andthelayoutandstyleofthebackground.Toadjustsettingssuchasdesktopcolourandbackground,useyourrightmousebuttontoclickanywhereonthedesktop,andthenclickProperties.Figure33.4showsanexampleofthePropertieswindow.
FIGURE33.3 Exampledesktopscreen
FIGURE33.4 Exampledesktopscreen
• NetworkNeighborhood.Windows95/NThasextensivesupportfornetworking.IfanetworkispresentthentheNetworkNeighborhoodiconappearsonyourdesktop.Theusercanthenbrowsetheentirenetworkbydouble-clickingtheicon.
• MyComputer.TheMyComputericonallowsquickandeasyaccesstothecomputer.Theusercanbrowsethroughthefilesandfoldersbydouble-clickingtheMyComputericon.
• WindowsExplorer.Thisisaprogramthatallowstheusertoviewboththehierarchyoffoldersonyourcomputerandallthefilesandfoldersineachselectedfolder.Itistypicallyusedtocopyandmovefiles,wherefilescanbedraggedintoaspecificfolder.
•Properties.EachiconwhichappearsinWindows95/NThasassociatedproperties.Itviewsthepropertiesthentherightmousebuttonclicksontheitem,andthenclicksPropertiesfromthepop-upmenu.
•Shortcutmenus.Ashortcutmenuisdisplayedwhentheuserclickstheright
mousebuttononanitem.Thismenuallowstheusertoopen,copyordeletetheitem.
•Close,Minimize,andMaximizebuttons.Eachwindowhasaclosebuttonintheupper-rightcornerwhich,whenclicked,willclosethewindow
andquittheprogram.Thewindowscanalsominimizeormaximize .Thecurrentactivewindowhasabluetitlebarwhilstaninactivewindowhasa
greytitlebar.Onlyiconswithinanactivewindowcanbeselected.
33.8MousecontrolsThemousecontrolsthepointeraroundthescreen.AswithpreviousversionsofWindows,adoubleclickoftheleftmousebuttononaniconisusedtoeitherrunanapplicationandasingleclicktoselectawindoworfile.
33.9QuittingWindowsThe usermust shutWindows down before switching off the computer. To dothistheuserselectstheShutDown…optionfromtheStartbar.Thentheuserwillbegivenanumberofoptions,asshowninFigure33.5.Iftheuseristoquitand switchoff then theShutdown the computeroption is selected andYes isselected.
FIGURE33.5 QuittingWindows
33.9.1GettingHelpThe best method of getting help is to refer to the user manual. If that is notavailablethenthereison-linehelp.Theon-linemanualisavailablebyselectingthehelpmanualicon.
33.10MovingandresizingawindowTheoptionusedtochangethewindowssizeare:•Maximizingawindow.Awindowcanbemadetofillthecompletescreenby
selectingthe atthetopright-handcornerofthescreen.•Minimizingawindow.Awindowcanbeminimizedtoaniconusing•Makingawindowsmaller.Ifawindowisfillingthecompletescreenitcan
bemadeintoasmallerwindowbyselecting•Movingawindow.Awindowcanbemovedbyplacingthemousepointeron
thebluetitlebar.Theleftmousebuttondownispressedwhilemovingthewindowtoitsrequiredposition,thenthemousebuttonisreleased.
•Resizingawindow.Awindowcanberesizedbyplacingthemousepointereitheratoneofthecornersorthesides.Thepointershapeshouldchangewhenitisplacedovertheborderofthewindows.Toexpand(orcontract)thewindowverticallythemousepointerisplacedeitheratthetoporbottomborder.Themouseisthenpressedwhilemovingtheborderofthewindows.Whentherequiredpositionisfoundthemousebuttonisreleased.Asimilaroperationcanbeconductedtoexpand(orcontract)horizontally.
33.11ClosingawindowwiththeControlmenuTheControlmenuisactivatedbyselectthetopleft-handbuttononthewindow.Thismenucontainstheoptions:Restore,Move,Size,Minimize,MaximizeandClose. The Restore, Move, Size, Minimize and Maximize options mimicoperationsthatareconductedbythemouse.AusefuloptionistheClosewhichexitsfromthewindowandclosesitdown;thisisshowninFigure33.6.
FIGURE33.6 Controlmenu
33.12StartTheStartbuttonat thebottomleft-handside isusedtoquicklyrunapplicationprograms.AnexampleStartbarisshowninFigure33.7.
FIGURE33.7 Examplestartoptions
33.13MyComputerTheMyComputerwindowallowsaccesstolocaldisks,suchasthefloppydiskand hard disks, printers,CD-ROM, and so on. Figure 33.8 shows an examplewindow.
FIGURE33.8 ExampleMyComputer
33.14RunningDOSWindowsNT/95runsanemulatedversionofDOS.ThisistypicallyusedtorunDOS-basedprogramandalsotorunDOScommands.Figure33.9showshowaDOSwindow is initiated. It can either run in awindow or full-screen. Figure33.10showsasampleDOSwindow.
33.15Windows95/NTnetworkdrivesWindowsNTand95displays thecurrentlymountednetworkdriveswithin thegroupMyComputer. Figure 33.11 shows driveswhich are either local (C:D:andE:)ormountedusingNetWare(F:G:andsoon).WindowsNTand95alsoautomatically scan the neigbouring networks to find network servers. Anexample is shown in Figures 1.12 and 1.13. Figure 33.13 shows the currentlymountedservers(suchas,EECE_l)andbyselectingtheGlobalNetworkiconalltheotherconnectedlocalserverscanbeshown.
FIGURE33.11 Mountednetworkandlocaldrives
FIGURE33.13 Localneighbourhoodservers
FIGURE33.12 Networkneighbourhood
33.16ExercisesConductthefollowingstepsfillingintherequiredinformation.33.16.1.Windowsversion.Windows95[]WindowsNT[]Other[]33.16.2.Networkedcomputer.Yes[]No[]33.16.3.Identifyeachoftheiconsonthedesktop:33.16.4.SelectMyComputerandresizeitsothatitfillsthescreen.Ticboxif
completesuccessfully.Completedsuccessfully[]
33.16.5.ResizeMyComputersothatitisshownatitsnormalpositiononthescreen.
Completedsuccessfully[]33.16.6.IconizeMyComputerandthenrestoreittoitsnormalposition.Completedsuccessfully[]33.16.7.ExpandMyComputerhorizontally,thenrestoreittoitsnormal
position.Completedsuccessfully[]33.16.8.ContractMyComputerwindowvertically,thenrestoreittoitsnormal
position.Completedsuccessfully[]33.16.9.Findthefollowingapplicationprograms,runthemandthenexit.Tic
boxifcompletesuccessfully.
33.16.10.OpenaDOSwindowandmovearoundthefilesystem.Listsomeofthedirectoriesonthesystem:
33.16.11.ExitfromWindows.Completedsuccessfully[]33.16.12.StartWindowsagain.Completedsuccessfully[]33.16.13.Thereisanon-linehelpfacilitywithinWindows.Toselectthis,use
theHelpmenuoptionwithintheProgramManager.Usethisfacilitytofindhelponthefollowingtopics.
Quittingwindows:_____________________
Deletingfolders:_____________________Startingapplications:______________________Deletingprograms:______________________
34
ExtraWindows
34.1Savingimportantset-upfiles
Windows 3.x and Windows 95/NT store important program configurationinformationinINIfile.Thesearenormallyeitherstoredinthedefaultwindowsdirectory or in the home directory of the application. The important files forWindowsconfigurationare:•SYSTEM.INI.Thiscontainsinformationontheconfigurationofvarious
programsandalsoprogramswhichareinitiatedwhenWindowsisstarted.
•WIN.INI.Thiscontainsinformationofthedesktop,suchasthegroupswhicharedisplayed,theirpositiononthedesktopandtheirsize.
Itisimportanttobackuptheinitializationfilesasthesecanbeeasilymodifiedby mistake. Initialization files have a INI extension and are stored in the\WINDOWS directory.Tomake a backupof these files create a directorynamedINIasasubdirectoryofthe\WINDOWSdirectorycancopytheseINIfilesintoit.Ifoneofthesefilesismodifiedbymistakeit isasimpletasktocopyanolderversionback into the\WINDOWSdirectory.Thisprocedure is shown inTest run34.1.
34.2RunningaprogramwhenWindowsstartsupProgramscanbeinitiatedwhenWindowsisstarted.Typicalprogramswhichcanbeloadedaretheclock,awordprocessor,aspreadsheetoracalendar.Thiscanbe achieved by selecting the following folder: Selecting Windows→StartMenu→Programs→StartUpThenthestartupitemisaddedbyeitherdraggingitintotheStartUpfolderor
byselectingFile→New.
FIGURE34.1 AddingtotheStartUpfolder
InWindows3.1itisselectedby:•TheapplicationiconcanbeinsertedintotheStartUpgroupsothatitwill
automaticallystartwhenwindowsisstarted.TocreateanewStartUpgroup,selectFile>NewfromProgramManager,asillustratedinFigure34.2.NextselectagroupandnameitStartUp.Iconscanthenbedraggedfromanothergroupintothisone.
FIGURE34.2 CreatingaStartUpgroup
Oncethestartupgrouphasbeeninitiatedanemptywindowshouldbedisplayed.Tomoveaprogrampointtoitwiththecursorthenholdthe
firstmousekeydownanddragitintotheStartUpgroup.Iftheprogramistobecopied(andnotmoved)thenholddowntheCtrlkeyastheiconisdragged.Figure34.2showsaStartUpwindowswiththeCalendarandClock.
AprogramcanalsobeautomaticallystartedbyeditingtheWIN.INIfilesothattheprogramname is insertedafter therun=directive.Forexample, to run theclockandWordforWindowsthefollowingcanbeinserted:
Toloadaprogramwhichisminimized(thatis,itwillappearasaniconatthebottom of the screen) the load= directive is used. For example, to start theprogramsWord forWindows 6.0 andcardfile the following can be insertedintotheWIN.INIfile
34.3CapturingWindowsscreenTherearetwohotkeysset-upinWindowstocapturescreens:•PrintScreenkeycapturesacompletescreen.•Alt-PrintScreencapturesonlythecurrentwindow.These captured screens are put into the clipboard. Figure 34.3 shows the
ClipboardViewerscreenafterascreenhasbeencapturedfromMicrosoftWordforWindows2.0.Thecontentsoftheclipboardcanbeimportedintoadocumentorother applicationbypasting.This can eitherbedoneby selecting thePastefromamenuorCtrl-V.
FIGURE34.3 ContentsofClipboardViewerafterascreenhasbeencaptured
34.4SwappingbetweenapplicationsThe Alt-TAB hot key can be used to switch between one application andanother.Forexample:
1.Runanapplication.2.PressAlt-TABtocyclethroughtheWindowsapplicationsonthedesktop.
Thenameoftheapplicationappearsatthetopofthescreen.Figure34.4 showsanexampleof swappingbetweenaWindows screenand
anotherapplication.
FIGURE34.4 Swappingbetweenapplications
34.5TerminatingprogramswhichhavecrashedIf a programhas crashed it cannormally be terminatedusing theCtrl-Alt-Delkeystrokes.IfWindowsisstillrunningitwilldisplayabluescreenwhichasksthe user to either press <RETURN> if the program is to be terminated to useCtrl-Alt-Deltorebootthesystem.Normallyit isonlyrequiredtoterminatethecrashedprogramsopress<RETURN>.
34.6WindowsfileextensionsWindowsusesalargenumberoffiletypes.Table34.1givesthebasicfiletypeextensions.
Table34.1Fileextensions
34.7Exercises34.7.1.StartthecalculatorprogramandthenpressCtrl-Alt-Del.Confirmthata
similarscreentotheoneshowninFigure34.5.Nextshutdowntheprogram.
FIGURE34.5 Closinganapplication
Completedsuccessfully[]34.7.2.IdentifysomeINIfilesandtheapplicationprogramthattheyarelikelyto
belinkedto.Completedsuccessfully[]34.7.3.ListsomeoftheWIN.INIandSYSTEM.INIfiles.Identifysomeofthe
linesinthesefiles.Completedsuccessfully[]34.7.4.RuntheCalculatorandNotepadprograms(fromtheAccessoriesgroup)
andusetheAlt-TABkeystroketoswapbetweentheseapplications.Completedsuccessfully[]
34.7.5.WiththeCalculatorprogram,determinethefollowing:(i)54×32
(ii)1043254(iii)√l63Completedsuccessfully[]
34.7.6.WiththeNotepadprogram,createafilecalledMYFILE.TXTandaddthefollowingtext:
Completedsuccessfully[]34.7.7.QuittheCalculatorandNotepadprograms.Completedsuccessfully[]34.7.8.LocatetheMYFILE.TXTfileandopenittoseethatitcontainsthe
enteredtext.Completedsuccessfully[]34.7.9.ClosetheNotepadprogram.Completedsuccessfully[]34.7.10.Fromtheoperatingsystem,changethenameofMYFILE.TXTto
MYFILE2.TXT.Completedsuccessfully[]34.7.11.Fromtheoperatingsystem,copytheMYFILE2.TXTfileinto
MYFILE3.TXTfile.Completedsuccessfully[]34.7.12.FormatafloppydiskandcopytheMYFILE2.TXTfileontoit.Completedsuccessfully[]
35
IntroductiontoUNIX
35.1Introduction
UNIX is an extremely popular operating system and dominates in the high-powered,multitaskingworkstationmarket. It is relatively simple touseand toadminister,andalsohasahighdegreeofsecurity.UNIXcomputersuseTCP/IPcommunications to mount disk resources from one machine onto another. Itsmaincharacteristicsare:•Multi-user.•Pre-emptivemultitasking.•Multi-processing.•Multi-threadedapplications.•Memorymanagementwithpaging(organizingprogramssothattheprogram
isloadedintopagesofmemory)andswapping(whichinvolvesswappingthecontentsofmemorytodiskstorage).
The two main families of UNIX are UNIX System V and BSD (BerkeleySoftwareDistribution)Version4.4.SystemVistheoperatingsystemmostoftenusedandhasdescendedfromasystemdevelopedbytheBellLaboratoriesandwasrecentlysoldtoSCO(SantaCruzOperation).PopularUNIXsystemsare:•AIX(onIBMworkstationsandmainframes).•HP-UX(onHPworkstations).•Linux(onPC-basedsystems).•OSF/1(onDECworkstations).•Solaris(onSunworkstations).Aninitiativebyseveralsoftwarevendorshasresultedinacommonstandard
fortheuserinterfaceandtheoperationofUNIX.Theuserinterfacestandardisdefined by the common desktop environment (CDE). This allows softwarevendors to write calls to a standard CDEAPI (application specific interface).ThecommonUNIXstandardhasbeendefinedasSpec1170APIs.Compliancewith the CDE and Spec 1170 API is certified by X/Open, which is a UNIX
standardorganization.
35.2LoginintothesystemInorder toconnect to thesystemavaliduser IDandapasswordare required.Theseareassignedinitiallybythesystemmanager.InSamplesession35.1theuserbill_b logsinwiththecorrectpassword.IftheuserIDandpasswordarevalid then system messages are then displayed in a start-up screen (such assystem shut-downs, holiday arrangements, and so on) and the command lineprompt is displayed (in this case[51:miranda:/net/castor_win/local_user/bill_b]%). The computer is nowreadyforacommand.
35.3DirectorystructureFilesareusedtostorepermanentinformationwhichareusedbyprograms.Theinformation could be schematics, text files, documents, and so on. In order tofacilitatetherecoveryoffilestheyarearrangedintodirectoriesinastructurethatissimilartoanofficefilingsystem.TheUNIXfiledirectorystructuretakestheformofatreewiththerootdirectoryatthehighestlevel.Thistoplevel,orrootdirectory, is given the name /.An example of a directory system is shown inFigure35.1. In this case thereare5 sub-directoriesbelow the root level, these
are bin, usr, etc, dev and user. Below the usr directory there are 3 sub-directories, theseare lib, admandbin. In thiscase,all theusersof the systemhave been assigned to a sub-directory below the users directory, that is,bill_b,fred_aandalan_g.
FIGURE35.1 Basicdirectorystructure
The full pathname of the bill_b directory is /users/bill_b and the fullpathname of the adm directory is usradmin. Files can be stored within adirectorystructure.Figure35.2showsanexamplestructure.
FIGURE35.2 Basicdirectorystructureshowingfileswithindirectories
Inthiscase,thefullpathnameoftheFORTRANfileprog.ftnis:
andthefullpathnameofthecdirectoryis:
Files and sub-directories canalsobe referred to ina relativemanner,wherethedirectoryisnotreferencetothetop-level(itthusdoesnothaveapreceding/).Forexample,iftheuserwasinthebill_bdirectorythentherelativepathfortheCprogramfile1.cis:
35.4On-linemanualUnix provides an on-line manual to give information on all the UNIX
commands.Togetinformationmancommand-nameisused,suchas:
Examples are man 1s, man cd, and so on. Sample session 35.2 shows anexampleofthehelpmanualforthe1scommand.
35.5ChangingdirectoryThepwdcommandcanbeusedtodeterminethepresentworkingdirectory.andthe cd command can be used to change the current working directory.Whenchangingdirectoryeitherthefullpathnameortherelativepathnameisgiven.Ifa/precedesthedirectorynamethenitisafullpathname,elseitisarelativepath.Somespecialcharactersequencesareusedtorepresentotherdirectory,suchasthedirectoryabovethecurrentdirectoryisspecifiedbyadoubledot(..).Thustomovetothedirectoryabovethecommandcd..canbeused.Ifthecd
command is usedwithout any preceding directory specifier then the directorywillbechangedtotheuser’shomedirectory.Someexamplecommandsessionsaregivennext.
35.6ListingdirectoriesThelscommandliststhecontentsofadirectory.Ifnodirectory-nameisgiventhen it lists thecontentsof thecurrentdirectory.Sample session35.3 showsatypicalsession.In[5]theusermovestothedirectoryaboveandin[11]theusermovebacktothehomedirectory.
Thebasicdirectorylistinggivesnoinformationaboutthesizeoffiles,ifitisadirectory,andsoon.Tolistmoreinformationthe–1optionisused.Anexamplesession is shown in Sample session 35.5. In [15] the user requests extendedinformationonthefiles.
Otheroptionscanbeusedwithls;togetafulllistusetheon-linemanual.InSamplesession35.1itwasseenthatotherpossibleextensionsareabcdfgilmnopqrstuxACFHLR1.Examplesofusageare:
Itisalsopossibletospecifymorethanoneextension,suchas1s–drwhichlistsonlydirectoriesinreverseorder.
35.7FileattributesUNIXprovidessystemsecuritybyassigningeachfileanddirectorywithasetofattributes. These give the privileges on the file usage and their settings aredisplayedwiththe1s–1command.Inthecaseof[15]inSamplesession35.4,theuseruses1s–1togetextendedinformation.Thedirectorylistinggivessixmainfields;theseare:•Fileattributes.•Ownerofthefiles.Person(userID)whoownsthefile.•Groupinformation.Thegroupnamedefinesthenameofthegroupthegroup
theattributesconcern.•Sizeoffile.Thesizeofthefileinbytes(8bits).•Dateandtimecreatedorlastmodified.Thisgivesthedateandtimethefile
waslastmodified.Ifitwasmodifiedinadifferentyearthentheyearanddatearegiven,butnotimeinformationisgiven.
•Filename.Figure35.3definestheformatoftheextendedfilelisting.Thefileattributes
contain the letters r, w, x which denote read, write and executable. If theattribute exists then the associated letter is placed at a fixed position, else a –appears.Thedefinitionoftheseattributesareasfollows:
FIGURE35.3 Extendedfilelisting
•Read(r).Thisfilecanbecopied,viewed,andsoon,butitcannotbemodified.
•Write(w).Thisfilecanbecopied,viewedandchanged,ifrequired.Executable(x).Itispossibletoexecutethisprogram.
Thefileattributessplitintofourmainsections.Thefirstpositionidentifiesifit is a directory or a file.A d character identifies a directory, else it is a file.Positions 2–4 are the owner attributes, positions 5–7 are the groups attributesandpositions8–10are the restof theworld’s attributes.Table35.1 lists someexamples.
Table35.1Examplefileattributes
Attributes Description
-r-x–x— Thisfilecanbeexecutedbytheownerandhisgroup(e.g.staff,students,admin,research,system,andsoon).Itcanbeviewedbytheownerbutno-oneelse.Nootherprivilegesexist.
drwxr-xr-x Thisdirectorycanbecannotbewrittentobythemembersofgroupandothers.Allotherprivilegesexist
-rwxrwxrwx Thisfilecanbereadandwrittentobyeveryoneanditcanalsobeexecutedbyeveryone(bewareofthis).
35.7.1ChangingAttributesOfAFileAswehaveseen,fileshavecertainattributessucharead/writeprivileges,andsoon.Thechmodcommandcanbeusedbytheownerofthefiletochangeanyofthe
fileattributes.Ageneralformatisgivennext.
wheresettingsdefinehowtheattributesaretobechangedandwhichpartoftheattributetochange.Thecharacterswhichdefinewhichparttomodifyareu(user),g(group),o(others),ora(all).Thecharactersforthefileattributesareasign (+, – or =) followed by the characters r, w, x. A ‘+’, specify that theattributeistobeadded,aspecifiesthattheattributeistobetakenaway.The‘=’definestheactualattributes.Someexamplesaregivennext:
InSamplesession35.5[20]theownerofthefilechangestheexecuteattributefortheuser.
35.8Specialcharacters(*,?and[])Thereareseveralspecialcharacterswhichaidaccesstofiles.ThesearestatedinTable35.2.
Table35.2Specialcharacters
Char Description
? matchesanysinglecharacterinafilename.
* matcheszeroormorecharactersinafilename.
[] matchesonecharacteratatime,thesecharactersarecontainedinthesquaredbrackets.
Samplesession35.6showsafewsampleusesofwildcards. In[24] theuserlistsallthefileswhichbeginwiththeletter‘m’.In[26]alltwoletterfilenamesbeginningwith‘c’arelisted.Thenin[27]thefileswhichbeginwiththeletters‘a’,‘b’or‘c’arelisted.
Notethat[a–c]represents[abc]and[1–9]represents[123456789].
35.9ListingcontentsofafileThecommandtolistthecontentsofafileiscat,itsformis:
Samplesession35.7showshowit isused. Ifafile is larger thanonescreenfullitispossibletostopthetextfromscrollingbyusingCntl-S(⁁S)tostopthetextandCntl-Q(^Q)tostart.
35.10MakingandremovingdirectoriesTomakeadirectorythemkdircommandisused,itsformis:
toremoveadirectorythermdircommandisused,itsformis:
Inbothcasesthefullpathnameorrelativepathnamecanbegiven.
35.11Copying,renamingandremovingThecommandtocopyfilesisthecpcommand.Thestandardformatis:
andthecommandtorename(ormove)iscalledmv.Itsstandardformatis:
Files are erased, or deleted, using the rm command. Sample session 35.8showssomeusesofthesecommands.
35.12StandardinputandoutputThe standard input device for a program is via the keyboard and the standardoutput is to themonitor. InUNIX all input output devices are communicatedwiththroughadevicefile,whicharestoredinthe/devdirectory.Forexample,each connected keyboard to the system (including remote computers) has adifferent device name.To determinewhich is your terminal pathname use thettycommandasshowninSamplesession35.9.
35.12.1RedirectionItispossibletodirecttheinputand/oroutputfromaprogramtoanotherfileordevice.
RedirectingoutputTheredirectionsymbol(>)redirectstheoutputofaprogramtoagivenfile(oroutputdevice).Thisoutputwillnotappearonthemonitor(unlessitisredirectedtoit).Samplesession35.10showshowtheoutputfromadirectorylistingcanbesendtoafilenameddirlist(see[57]).Thecontentsofthisfilearethenlistedin[58].
Theredirectionofoutputisparticularlyusefulwhenaprocessisrunningandanoutputtothescreenisnotrequired.Anotheradvantageofredirectionisthatitispossibletokeepapermanentcopyofaprogram’sexecution.Tocreateatextfilethecatcommandisusedwiththeredirection,asshown
next.ThefileisclosedwhentheuserusestheCNTRL-Dkeystroke,asshowninSamplerun35.11.If the user does notwant the output to appear on the screen then it can be
redirectedtothefilecalleddevnull.Thisisthesystemswastepaperbasketanditwillautomaticallybedeleted.
RedirectinginputTheinputcanberedirectedwiththeredirectsymbol(<).Thefilegivenafterthesymbolistakenastheinput.Forexample:
Inthiscasetheprogramprog1takesitsinputfromthefileinputfile,andnotfromthekeyboard.
35.12.2PipesThepipeallowstheoutputofoneprogramtobesenttoanotherastheinput.Thesymbolusedistheverticalbar(|)anditsstandardformis:
This notation means that the output of program_a is used as the input toprogram_b.Thepipehelps in commandswhere a temporary file/s needs tobecreated. For example, to find out who is logged into the system the who –acommand can be used. If names in a file need to be sorted alphabetically thesortcommandcanbeused.Thustosorttheusersonthesystemalphabeticallywecanuse:
Itispossibletoachievethiswithonelineusingpipes.
35.13CompilingCprogramsThecccommandisusedtocompileandlinkaprogram.IftherearenoerrorsintheCsourcecodethen,bydefault,afilenameda.outwillbeproduced.Thiscanthen be executed. If another executable filename is required then the -ofilename option can be used. Sample session 35.14 shows how the C filefile.ciscompiledandlinkedtoanexecutablefilenamedfile.
35.14DisplayingthetimeanddateThe command to display the date is simply date. This is shown in Samplesession35.15.
35.15WheretofindthingsUNIXhasvariousdefaultdirectorieswhichstore standardcommandprogramsandconfigurationfiles.Someofthesearedefinedinthefollowingsections.
35.15.1/BinThe/bindirectorycontainsmostofthestandardcommands,suchascompilers,UNIXcommands,programdevelopmenttools,andsoon.Examplesare:•FORTRANandCcompilers,f77andcc.•commandssuchasar,cat,manutilities.
35.15.2/Dev
The /dev directory contains special files for external devices, terminals,consoles,lineprinters,diskdrives,andsoon.
35.15.3/EtcThe/etcdirectorycontains restrictedsystemdataandsystemutilityprogramswhicharenormallyusedby the systemmanager.These includepassword file,login,andsoon.Examplesare:
35.15.4/LibThe /lib directory contains system utilities and FORTRAN and C runtimesupport,systemcallsandinput/outputroutines.
35.15.5/TmpTemporary (scratch) files used by various utilities such as editors, compilers,assemblers.Thesearenormallystoredinthe/tmpdirectory.
35.15.6UsradmTheusradmstoresvariousadministratorsfiles,suchas:
35.15.7UsrbinTheusrbincontainslessusedutilityprograms,suchas:
35.15.8UsrincludeTheusrincludedirectorycontainsC#includeheaderfiles,suchas:
35.15.9UsrlibTheusrlibdirectorycontainslibraryroutinesandsetupfiles,suchas:
35.15.10UsrmanTheusrmancontainsthemanualpages,suchas
35.16Exercises35.17.1.Gotoyourhomedirectory.
35.17.2.Displaythecurrentsystemdate.
35.17.3.Displaytheon-linehelpmanualforthefollowingcommands:
Completedsuccessfully:YES/NO35.17.4.Listalltheuserscurrentlyloggedintothesystem.
35.17.5.Createadirectorynamedsrcinyourhomedirectory.35.17.6.Gointothedirectorysrcandcreateasub-directorynamedcprogs.35.17.7.Gointothecprogsdirectoryandcreateafilenamedfile1.cusingcat
(orthesystemeditor).Enterthefollowingtextandsavethefile.
35.17.8.Listthefileyouhavejustcreated.Completedsuccessfully:YES/NO35.17.9.Changethenameofthisfiletofile2.c.Completedsuccessfully:YES/NO
35.17.10.Makeacopyofthisfileandnameitfile3.c.Completedsuccessfully:YES/NO35.17.11.Changethefileattributesofthisfilesothatthepubliccannotread
fromorwritetothisfile.35.17.12.Createanothernamedfile2.candenterthefollowingsourcecode.
35.17.13.Concatenatethetwofilestogether.Calltheresultantfilesrc.lis.Completedsuccessfully:YES/NO35.17.14.CompileandrunthetwoCprogramsjustcreated.Completedsuccessfully:YES/NO35.17.15.Removethefilesrc.lisCompletedsuccessfully:YES/NO35.17.16.Investigatethefollowingcommands/utilities:
35.17.17.Locatethefollowingutilityfilesanddeterminetheirusage.
35.17.18.Sketcharoughoutlineofthedirectorystructureofthesystem.
35.17SummaryTable35.3listssomestandardUNIXcommands.
Table35.3Commandssummary
Command Description
mansubject on-linemanualonsubject
ls listofadirectory(−1longlisting;–aall;–rreverselisting.
cd changedirectory
mv movefile
cp copyfile
mkdir makedirectory
pwd presentworkingdirectory
cat concatenateafile/s
>file redirectoutputtofile
<file redirectinputfromfile
36
UNIXCommands
36.1Processcontrol
UNIX is amultitasking,multiuseroperating system,wheremany tasks canberunningatacertaintime.Typicallythereareseveralprocesseswhicharestartedwhenthecomputerisrebooted;thesearenameddaemonprocessesandtheyrunevenwhenthereisnouserloggedintothesystem.
36.1.1Ps(ProcessStatus)Thepscommandprintsinformationaboutthecurrentprocessstatus.Thebasicpslistgivesalistofthecurrentjobsoftheuser.AnexampleisgiveninSamplesession36.1.
The informationprovidedgives theprocess identificationnumber (PID), theterminalatwhichtheprocesswasstarted(TTY),theamountofCPUtimeusedandthecommandlinethatwasentered(CMD).Aprocesscanbestoppedusingthekillcommand.Alonglistingisachievedusingthe–1optionandforacompletelistingofall
processesonthesystemthe–aoptionisused,asshowninSamplesession36.2.
ThecolumnheadedSgives thestateof theprocess.AnS identifies that theprocess is sleeping (the system is doing something else),W specifies that thesystemiswaitingforanotherprocesstostopandRspecifiesthattheprocessiscurrentlyrunning.Insummary:•Rprocessisrunning.•Tprocesshasstooped.•Dprocessindiskwait.•Sprocessissleeping(thatis,lessthan20secs.).•Iprocessisidle(thatis,longerthan20secs.).UID is the user identity number. PRI is the priority of the process.A high
numbermeansalowpriority.
36.1.2Kill(SendASignalToAProcess,OrTerminateAProcess)Thekillcommandsendsasignaltoaprocess.Thegeneralformatis:
Theprocessidisthenumbergiventotheprocessbythecomputer.Thiscanbefoundbyusing thepscommand.Thesigvaluedefines theamountof strengththatisgiventothekillprocessandthestrongestvalueisa–9.Theownerofaprocess can kill his own, but only the superuser can kill any process. Samplesession36.3givesanexamplesession.
36.1.3At(ExecuteCommandsAtLaterDate)Theatcommandwhenusedinconjunctionwithanothercommandwillexecutethatcommandatsomelatertime.Thestandardformatis:
wheretimeisgivenusingfrom1to4digits,followedbyeither‘a’,‘p’,‘n’or‘m’foram,pm,noonormidnight,respectively.Ifnolettersaregiventhena24-hour clock is assumed. A 1-or 2-digit time is assumed to be given in hours,whereasa3-or4-digit time is assumed tobehoursandminutes.Acolonmayalsobeincludedtoseparatethehoursfromtheminutes.TheDate can be specified by themonth followed by the day-of-the-month
number,suchasMar31.AWeekcanbegiveninsteadofthedayandmonth.Forexample,tocompileaprogramatquarterpasteightatnight:
andtosendfredamessageat14:00:
To remove all files with the .o extensions from the current directory onSeptember9that1noon.
To list all jobs that are waiting to executed at some later time use the –1option.
Toremove jobs fromtheschedule the–roptioncanbeusedandgiving thejobnumber.
36.1.4Nice(RunACommandAtALowPriority)Thenicecommandrunsacommandatalowpriority.Thestandardformatisasfollows:
Thelowestpriorityis–20andthedefaultis–10.Samplesession36.9givesasamplesession.
36.2CompilersThetwomaincompilersonUNIXsystemsareC(cc)andFORTRAN(f77).
36.2.1Cc(CCompiler)ThecccommandistheClanguagecompilerandisusedtoconvertaCprograminto binary code. It can also link several binarymodules together tomake anexecutablefile.Fileswiththeextension.caretakenasCprogramsandwhenaCprogramis
compiled theresultingbinarymodule(theobjectcode) isplaced in thecurrentdirectory.Ifa–coptionisnotusedthebinarycodewillbecalleda.out.Ifthe–coptionisusedthebinarycodewill takethenamegiven,themodulesproducedwillhavea.oextension.Optionsare:–c.producesinglebinarymodule(objectcode)withtheextension.o.–o.outfitthisoptionisusedtogivethenamefortheoutputfile.–g.producedebuginformationforusewithadebugger(suchasdbx).In Sample session 36.11, the first example of the C program progl.c is
compiled;theresultingfileproducediscalleda.out.Thisfilecanbeexecutedas required. The second type of compilation (cc –c *.c) compiles all the Cprograms and produces an object module with a .o extension. These objectmodulescanbelinkedtogetherusingthecompiler.Thelastexample(cc–oprogprog1.oprog2.o) linkstogethertheobjectmodulesforprog1.candprog2.c.Theexecutableprogram,inthiscase,willbecalledprog.
36.2.2F77(FORTRANCompiler)The FORTRAN compiler f 77 is used to compile and/or link FORTRANprograms.Thesourcefileisassumedtohavethe.fextension.Ifthe–coptionischosenthecompiledmodulewillhavethe.oextension;thisisanobjectmodule.Samplesession36.11givessomeexamples.
36.2.3Dbx(DebuggerForC,FORTRANAndPascal)The dbx utility is a source-level debugger for C, FORTRAN and Pascal. Itallows the user to trace a program’s execution and list variables. The generalformatis:
Somecommandsfordbxare:
run runsthecurrentprogram.
step stepthroughtheprogramexecutiononelineatatime.
cont continueprogramexecutionwhereitstopped.
print printcontentsofavariablesuchasprintinput_value.
list listnexttenlinesofcodeifnoargumentsaregiven;tolistfromlinestarttolineenduselistlinestart,lineend.
lineend.
help gethelpinformation.
trace traceprogramexecution.
quit exitdbx.
36.2.4Lint(CProgramVerifier)Thelint utility isused toverifyCprograms. It attempts todetectbugs,non-portablewarnings and anywasteful use ofC code.The basicC compiler,cc,doeslittleruntimecheckingorinefficiencychecking.Torunthelintprogram:
Samplesession36.12givesasamplesession.
36.3FilemanipulationcommandsUNIX has a number of file manipulation commands, some of which weredefinedinthepreviouschapterandmanyothersaregiveninthissection.
36.3.1Cp(CopyFiles)Thecpcommandwillcopyagivenfileordirectorytoagivenfileordirectory.Thereareseveraloptionsthatcanbeused:–iusesinteractivemode,theuserispromptedwheneverafileistobe
overwritten.Theuseranswers‘y’or‘n’.–rusesrecursivemode,thecpcommandallfilesincludingeachsubdirectoryit
encounters.Thefollowingexamplewillcopyafilecalledfile1intoafilecalledfile2.
Note that if file2 were a directory then file2 would be copied into thatdirectory.
Ifyouwanttocopyawholedirectoryandallsubdirectoriesthe–roptionisused. In the next example the whole directory structure of usrstaff/bill iscopiedintothedirectoryusrstaff/fred:
Tocopyafileintoadirectory:
36.3.2Is(ListDirectory)The ls command lists the contents of a directory. A summary of the variousoptionsaregivenbelow:
–a listsallentriesincludingfilesthatbeginwitha.(dot)
–l listsfilesinthelongformat.Informationgivenincludessize,ownership,groupandtimelastmodified.
–r listsinreversealphabeticorder.
–t listsbytimelastmodified(latestfirst)insteadofname.
–l listsoneentryperline.
–F marksdirectorieswithatrailingslash(/),executableswithatrailingstar(*).
–R recursivelylistssubdirectoriesencountered.
Samplesession36.16givessomeexamples.
36.3.3File(DetermineFileType)Thefilecommandisused to testa file for its typesuchasaCprogram, textfile,binaryfile,andsoon.Samplesession36.17givesatypicalsession.Typical
filetypesinclude:•mc68020demandpagedexecutable.•Cprogramtext.•ASCIItext.•Empty.•Archiverandomlibrary.•Symboliclink.•Executableshellscript.
36.3.4Du(DiskUsage)The du command lists the size of a directory and its subdirectories. If nodirectorynameisgiventhecurrentdirectoryisassumed.Twooptionsaregivennext:
36.3.5Cat(ConcatenateAndDisplay)The cat command concatenates and displays the given files to the standardoutput,whichisnormallythescreen(althoughthisoutputcanbechangedusingtheredirectionsymbol).Forexample,tolistafiletothescreen:
Toconcatenatetwofilestogether(file1.txtandfile2.txt)andputthemintoafilecalledfile3.txt:
If no filename is given then the input is taken from the standard input,normallythekeyboard.Ifaredirectsymbolisusedthenthisinputwillbesenttothegivenfile.Theendoftheinputisgivenbya⁁D(acontrol-D).Forexample:
36.3.6Compress,Uncompress(CompressAndExpandFiles)ThecompresscommandusestheadaptiveLempel-Zivcodingtoreducethesizeof a file. A.Z is added onto the filename so that it can be identified. Samplesession36.21showsanexample.
Thecontentsofthecompressedfilesareinacodedformsothattheycannotbe viewed by a text editor. The uncompress command can be used touncompress a compress file. Only files with the extension .Z can beuncompressed.
36.3.7Chmod(ChangeMode)FilesinUNIXhavevariousattributes;theseattributescanbesetorresetwiththechmodcommand.Theattributesare:
Owner Group Public
rwx rwx rwx
Theowneristhepersonwhocreatedthefileandthegroupisacollectionofseveralusers,suchasresearch,development,production,admingroups,andsoon.Thepublicisforeveryoneelseonthesystem.Therattributestandsforreadprivilegeandifitissetthenthefilecanberead
(that is, listed or copied) by that type of user.Thew attribute stands forwriteprivilegeandif it issetthenthefilecanbewrittento(thatis, listed,copiedormodified)bythattypeofuser.Thexattributestandsforexecuteprivilegeandifitissetthenthefilecanbeexecuted(thatis,itcanberun)bythattypeofuser.Forexample-rw-r–r–isafilethattheownercanreadorwritebutthegroup
andthepubliccanonlyreadthisfile.Anotherexampleis-r-x–x–x;withthese
attributestheownercanonlyreadthefile.No-oneelsecanreadthefile.No-onecan change the contents of the file.Everyone can execute the file.Thels -allistinggivesthefileattributes.
Thereareseveralways tochange theattributes.Thegeneral format isgivenbelow:
Thepermissioncanbesetbyusingtheoctalsystem.Ifanattributeexistsa1is set, if not it is set to a 0. For example,rw-r–r– translates to 110 100 100,whichis644inoctal.Forexample:
Tomakethefilefile.txtintorw-rw-r–:
TomakethefileRun_proginto–x–x—:
Theothermethodusedissymbolicnotation,thesearelistednext:
u userpermission
o others(public)permission
= assignapermission
– takeawaypermission
w writeattribute
g grouppermission
a allofuser,groupandotherpermissions+addapermission
r readattribute
x executeattribute
Forexample,tochangethefileRun_listsothatitcanbeexecutedbyalluse:
To take away readprivilege for all fileswith the .c extension for thegroupuse:
36.3.8Df(DiskSpace)Thedfcommandallowsyoutolisttheusageofthediskandallothermounteddiskdrives.Samplesession36.28givessomeexamples.
36.3.9Diff(DifferencesBetweenFiles)Thediffcommandshowsthedifferencebetweentwofilesortwodirectories.
Therearevariousoptionsusedandthesearesummarizednext:–iignoresthecaseofletters(suchas‘b’issameas‘B’).–wignoreallblanks(suchasfred=16.2issameasfred=16.2).Someexamplesarenext.Intheoutputlistingthe<characterreferstothefirst
file given and the > character refers to the second file given. A c refers to achange,adtoalinedeletedandanareferstotextthathasbeenappended.Thelinenumbersofthefirstfilealwaysappearfirst.
36.3.10Mv(MoveFiles)Themvcommandmovesfilesordirectoriesaroundthefilesystem.Thestandardformatsare:
Therearethreedifferentpermutations.Theseare:•Movingafileintoanotherfile(likerenaming).•Movingadirectoryintoanotherdirectory(likerenaming).•Movingafileintoanotherdirectory.Theoptionsthatcanbeusedare:
–i filesaremovedinteractively.Whenafileistobemovedthesystemwillprompttheuserastowhetherhewantstomovethefile.Iftheansweris’y’thefilewillbemoved,elseitwillnotbemoved.
–f forcemode;overrideanyrestrictions.
Samplesession36.30showsexamples.
36.3.11More(PageAFile)The more command allows the user to print one page of text at a time to thestandardoutput.Itpausesattheendofthepagewiththeprompt‘–More–’atthebottomofthepage.Samplesession36.31showssomeexamples.
36.3.12Rm(RemoveFilesOrDirectories)Thermcommandremoves filesordirectories.Toremoveadirectorywhich isemptythermdircommandcanbeused.Therearevariousoptions,suchas:
–f forcemode;removefileswithoutaskingquestions
–r recursivemode;deletecontentofadirectory,itssubdirectoriesand
thedirectoryitself;
–i interactivemode;asksquestionastowhethereachfileistobedeleted.
Samplesession36.32givessomeexamples.
36.3.13In(MakeLinks)TheIncommandmakesasoftlinktoafileordirectory.Whenthelinknameisusedthesystemwillgototheplaceindicatedbythelink.Thegeneralformatis:
Samplesession36.33showssomeexample.
36.3.14Find(FindFile)The find command searches recursively through a directory structure to findfilesthatmatchcertaincriteria.Itusesapathnamefromwheretostartseaching;thisisthefirstargumentgivenafterfind.Thenameofthefileisspecifiedafterthe–nameargumentandiftheuserwantsthefilesfoundprintedtothestandardoutputthe–printisspecifiedattheend.Samplesession36.34givesanexampleoffindingafilecalledfred.f,startingfromthecurrentdirectory.
Samplesession36.35showsasearchofthefilepasswd,startingfromthetop-leveldirectory.
Thewild-cardcharactercanbeusedinthenamebutthismustbeinsertedin
invertedcommas(”“).Samplesession36.36givesanexampleofsearchforallCfilesstartingwiththe/usr/staff/billdirectory.
Otherextensionscanbeusedsuchas–a timewhichdefines the timeof lastaccess.Theargumentfollowing–atimeisthenumberofdayssinceithasbeenaccessed.Samplesession36.37givesanexampleofsearchingforall.ofilesthathavenotbeenusedwithin10days.
36.3.15Grep(SearchAFileForAPattern)The grep commandwill search through given files looking for a given stringpattern. There are various options which can be used, a summary of these isgivenbelow:–vprintlinesthatdonotmatch;–xdisplayonlylinesthatmatchexactly;
–cdisplaycountofmatchinglines;–iignorecase.Samplesession36.38givessomeexamplesandthestandardformatis:
36.3.16Head(DisplaysFirstFewLinesOfAFile)Theheadcommandprintsthetopnlinesofafile.Thedefaultnumberis10linesandSample2.39givesexamples.Theformatisasfollows:
36.3.17Tail(DisplayLastPartOfFile)The tail command displays the last part of a file, where the first argumentdefines thenumberof lines tobedisplayed.Forexample, todisplay the last4linesofthefilefile1.txt:
36.3.18Wc(WordCount)Thewcutilitycountsthewords,charactersandlinesinafile.Ifseveralfilesaregiventhenthesumtotalof thefileswillbegiven.Thereare threeoptions thatcanbeused;thesearec,wand1,whichstandforcharacters,wordsandlines.
Ifnofilenameisgiventhenthekeyboardistakenastheinputandacontrol-Dendsthefileinput.Examplesare:
36.4Othercommands36.4.1Ar(ArchiveAndLibraryMaintainer)TheArCommandIsUsedToCreateAndMaintainLibrariesAndArchives.ALibraryIsAFileWhichContainsCompiledPrograms.TheseFilesAreCalledObjectModulesAndAreSelf-ContainedModules.TheObjectModulesHaveTheExtension.O.TheLibrariesAreUsedInTheLinkingProcess.
ThereAreCertainStandardLibrariesOnTheSystem;TheseIncludeTheStandardMathsLibraryAndStandardInput/OutputLibrary(NormallyFoundIn/Usr/Lib).
There are various options usedwith ar; these are given in Table 36.1. Forexample,tocreateanarchive
Table36.1aroptions
Option Description
d deletethenamedfilesfromthearchive
r replacethenamedfilesfromarchive
t listthecontentsofanarchive
x extractafilefromanarchive
c createanarchive
v extendedlistingoffile
Thentolistthearchive:
andtoextractafilefromthearchive:
Thenaddingallfileswith.cextension:
andlistingthearchiveagain:
Toextractafile:
andtocreatealibrarywith.oobjectmodules:
Archivesareusefulforkeepingmanyfilestogetherintheonefile.Thismakesthemusefulforprinting,storingontape,andsoon.ThesearestandardlibrariesontheUNIXsystem,suchas:
36.4.2Banner(MakePosters)Thebanner command prints thewords given on the screen in large letters.AsamplesessionisshowninSamplesession36.42.Themaximumlettersononelineisten.Itsstandardformis:
36.4.3Cal(Calendar)Thecalcommanddisplaysacalendarforagivenyearand/ormonth.Theyearmayvaryfrom1to9999andifnomonthoryearisgiventhecurrentmonthwillbe printed. Sample session 36.43 shows an example of displaying the currentmonthandSamplesession36.44displaysawholeyear.
36.4.4Chpass(ChangePassword)The chpass command is used to change the current login password. Samplesession36.45showsanexample.
36.4.5Date(DisplayOrSetDate)Thedatecommandeithergivesthecurrentdateandtimeorcanbeusedtosetthe current date and time (although only the superuser can do this). If noargumentsaregiventhenthecurrentdateandtimeisprinted.Ifavalidargumentisgiventhenthecurrenttimeischanged.Thegeneralformatisgivenbelow:
whereyyistheyear,mmisthemonth,ddisthedayofmonth,hhisthehour(24hourclock),mmistheminuteandssistheseconds(optional).It is possible to leave out various field such as the year and the seconds.
Samplesession36.46givessomeexamples.
36.4.6Echo(EchoArguments)Theechocommandwritesitsargumenttothestandardoutput.AC-likestandardis used for printing. Sample session 36.47 shows a few examples and thecharactersusedaregivenbelow:
36.4.7Finger(DisplayInformationOnUsers)The finger command gives information on a given user. This informationincludes:•Loginname.•Fullname.•Terminalname.•Idletime.•Logintime.•Officelocation.•Phonenumber,ifknown.Thefilesusedare:
36.4.8Ftp(FileTransferProgram)TheftputilityisthestandardFileTransferProtocol.Itisusedtotransferfilestoandfromaremotenetwork.Theformatis:
36.4.9Ipr(PrintFile)Thelprcommandspoolsafiletotheprinter.
36.4.10Mail(InteractiveMail)Themail utility is used to send and receivemessages from/to other users.Tosend mail the user’s name is simply specified after the program name. Forexample,tosendmailtoauserfred:
Whenever thecontrol-D(⁁D)keystroke isused then themessage issent toaspecifiedrecipient.Otheruserscanbesentthesamemailbysimplygivingtheirusernameasoneofthearguments,suchas:
Tosendafilewhichhasmailtheredirectsymbol(<)isused,suchas:
Whenreadingmail thesystemwill typically tell theuserwhen there ismailwaitingtoberead,suchas:
Thentoreadthemailthemailprogramisrun,suchas:Thentoreadthemailthemailprogramisrun,suchas:
Themail responsewithaquestionmark (?) isused to indicate that themailprogramiswaitingontheusertoenteracommand.Possibleoptionsare:
? displayhelpinformation
q quit
x exitwithoutchangingmail
p print
sfile savetofile
d deletemail
+ next(nodelete)
muser mailuser
36.4.11Passwd(ChangeLoginPassword)The passwd command is used to change the current password. Each user’spasswordisstoredinacodedforminetcpasswd.Eachnewpassword’smustbeat least5 characters long if they includeupper and lowercase,or6 if theyaremonocase.Samplesession36.53showsanexample.
36.4.12Pwd(PresentWorkingDirectory)
The pwd command prints the pathname of the current working directory.Examplesare:
36.4.13Rlogin(RemoteLogin)Therlogincommandallowstheuser to logintoaremotemachine.Theformatis:
36.4.14Sleep(SuspendExecutionForAnInterval)The sleep command is used to suspend to command for a given time. Thestandardformatis:
wherethetimeisinseconds.Samplesession36.55showsanexample.
36.4.15Spell(FindSpellingErrors)The spell utility finds spelling errors. TheUNIX dictionary resides in the file/usr/diet/words.Theformatisgivenbelow.
Therearevariousoptionsused:
-b Britishspelling(suchascolourinsteadofcolor).
-v verbose,fulllisting.
-X listseveryplausiblestemfordoubtfulwords.
Samplesession36.56showsanexample.
36.4.16Stty(SetTerminalOptions)Thesttycommandsetsuptheterminalcharacteristics.Therearetwomaintypesofoptions;thesearetogglesandsettings.Thestandardformatisgivenbelow.
Varioussettingsare:
even allowevenparity
odd allowoddparity
echo echoeverycharactertoscreen
icase convertcapitalletterstolowercase
tabs preservetabs
ek seteraseandshellcharactersto#and@
erasec seterasecharactertoc(usuallyB/S)
killc ,.setkillcharactertoc(usually@)
300,1200,andsoon setbaudrate
Samplesession36.57givesexamples.
36.4.17Tar(TapeArchiver)Thetarutilityallowsfilestobesaved,recoveredorlistedfromatapedrive.Itsstandardformis:
Optionsusedare:
c tocreatetapearchive
t tolisttapearchive
r torecovertapearchive
V completelistingoffilenames
Samplesession36.58showsexamples.
36.4.18Who(UsersLoggedIn)The who command lists all users on the system and which terminal they areusing.Thisinformationisfoundintheetcutmpfile.Iftheargumentsgivenaream i (that is, who am i) then the system prints details about the user. Forexample:
The informationgiven is theusername, terminal logged inonanddate thattheuserloggedin.
36.4.19Write(SendsMessagesToUsers)The write utility sends a message to a specified user. A control-D ends themessageinputandsendsit.Examplesare:
36.5Exercises36.5.1.LoginintheUNIXsystemanddeterminethecurrentprocessesthatthe
useriscurrentlyrunning.36.5.2.Determineallthecurrentprocessesthatarerunningandtheuserwhich
initiatedtheprocess.Identifythestatusoftheprocesses.36.5.3.Usethecat>newfilecommandandthentheCtrl-Zkeystroketo
suspendtheprocess.Showthattheprocesshasbeensuspended.
36.5.4.Killtheprocesswhichhasjustbeensuspended.36.5.5.Usingtheatcommand,runanIs–1atatimeoneminutefromthe
currenttime.36.5.6.Fromthecurrentdirectory,determinethefiletypesofthefiles.36.5.7.Fromthecurrentdirectory,determinethesizeofallthedirectories.36.5.8.Determinethepresentworkingdirectory.36.5.9.Determinethepresentdate.36.5.10.Listthecurrentdirectorysothatdirectorieshaveatrailingslash.36.5.11.Recursivelylistthecurrentdirectory,showingallsubdirectories.36.5.12.Determinetheuserswhoarecurrentlyloggedintothecomputer.36.5.13.Ifthereisauserloggedintothecomputerthensendanelectronic
messagetothem.36.5.14.Usingstty,determinetheterminalcharacteristics.36.5.15.Forthetop-leveldirectory,findalltheCprogramfiles.
37
EditingandTextProcessing
37.1Introduction
UNIX has several command programswhich can be used to edit and processtext.ThesearedefinedinTable37.1.
Table37.1Editingandtextprocessingprograms
Texteditors Textprocessing Textmanipulation
vi,thevisualeditor nroff,formatdocument grep,looksforapattern
ex,lineeditor troff,printformateddocument sort,sortslinesoftext
ed,lineeditor tb1,formattingtables spell,findsspellingerrors
sed,streamtexteditor pic,graphicslanguagefortypesetting
tr,translatescharacters
awk,patternscanningandprocessing
eqn,typesettingmathematics wc,countscharacters,wordsandlinesinafile.
37.2VisualeditorMost UNIX systems have their own text editor which is selected from theGraphical User Interface. The vi editor (pronounced vee-eye) is a text-basededitorandisstandardonallUNIXsystems.ItisnottheeasiesteditortousebutitisavailableonallUNIX-basedsystem.Theeditoriscalledwith:
37.2.1MakingChangesThe vi editor involves using special characters to identify editing commands.The user enters text only when the editor is in insert mode. All charactersenteredthismodeareaddedtothefile.Whennotininsertmodethecharactersare interpreted as editor commands. For example, an ‘x’ keystroke tells theeditortodeleteasinglecharacteranda‘d’followedbya‘w’deletesaword.
InsertmodeTo insert text the user must be in the insert mode. A summary of the maininsertionanddeleteoptionsisgivenbelow.Toinserttext,placethecursoronthecharacteryouwant to insertbefore thenpress ‘i’; thiswillputyou into insertmode.Thetextcanthenbeenteredwithasmanylinesasrequired.Toexitfrominsertmode,theESCkeyispressed,asillustratedinFigure37.1.Thisthenputstheeditorbackintonormalmode.Othermethodsofinsertionaresimilar,suchasan‘a’putsinsertedtextafterthecurrentcursorposition.While‘o’startsanewlineabovethelinetheuseriscurrentlyonand‘o’putsitafterthecurrentline.TheinsertmodecharactersarelistedinTable37.2.
Table37.2Editingandtextprocessingprograms
Option Description
i Enterinserttextmodebeforecursor.TheESCkeyisusedtoexitfrominsertmode.
Enterinsertmodeandcreateanewtextlineabovelineyouareon.
O Enterinsertmodebelowcurrentline.
a Enterinsertmodeaftercursor(thatis,append).
dd Deletewholeline.
X Deleteonecharacter.
dw Deleteword.
db Deletewordbefore.
ns Substitutesncharactersandentersintoinsertmode.
FIGURE37.1 Editandinsertmode
37.2.2DeletingTextDeletingtextisperformedintheeditmode.Thevariousmethodsare:•Deletelines.Asinglelineisdeletedwithtwo‘d’characters,thatis‘d’‘d’.
Todeleteseverallinesthenumberoflinestobedeletedisenteredfirstfollowedbytwo‘d’characters,suchas6‘d’‘d’deletes6lines
•Deletewords.Asingleword(asequenceofcharactersdelimitedbyspaces)isdeletedwitha‘d’followedby‘w’.Aswithdeletelines,severalwordsaredeletedbyenteringthenumberofwordstodeletefollowedbythe‘d’and‘w’characters.
•Deletecharacters.Asinglecharacterisdeletedwiththe‘x’character.Again,ifthischaracterisprecededbyanumberthenanumberofcharactersaredeleted.Forexample,5followedby‘x’deletes5characters.
37.2.3SubstitutingThe ‘s’ character identifies a substitution of characters. First the number ofcharacterstobesubstitutedisenteredandtheeditormarkstheendofthetexttobesubstitutedwitha$.Theeditoristhenputintoinsertmodeandthenewtextis entered followed by the ESC key. For example, to change fred to tom thecursorismovedtothefoffredandthentheusertypes4stom<ESC>.
37.2.4CutAndPaste(YankAndPut)The‘y’‘y’keystrokeisusedtocopyalineoftext(yank)andthe‘p’keystroke(put)isthenusedtoputthistexttoadefinedpartofafile.Thisisequivalenttocopythenpasteoperation.Iftheyankoptionisprecededbyanumberthenthatnumberoflinesareyanked.Forexample7‘y’‘y’stores7linesoftext.Notethatthe‘p’characterputslinesafterthepresentlineand‘P’afterthepresentline.
37.2.5UndoingThevi editor allows the last change to be undone. The keystroke for the lastoperation to be undone is ‘u’ and to restore awhole line the ‘U’ keystroke isused.
37.2.6MovingAroundTherearevariousmethodsofmovingaround theseareoutlined inTable37.3;andaredefinedas:
Table37.3Editingandtextprocessingprograms
Option Description
lor→ movecursorforwardonecursorposition
hor← movecursorbackoneposition
^b backwardsonepage
^f forwardonepage
^d scrolldownfile
^u scrollupfile
kor↓ nextline
jor↑ previousline
Gn gotolinenumbern
W forwardoneword
b backoneword
e endofcurrentword
w wordafterthisword
•Movingcursor.Thecursorcanbeusedwiththearrowkey(←,→,andsoon)iftheyaresupportedbytheterminalbeingused.Ifthekeyboardhasnoarrowkeys(ortheyarenotsupported)thenthecharactersusedare‘h’(left),‘j’(down),‘k’(up)and‘1’(right)keys
•Movingbypage.ThepagecanbemovedbackandforwardusingthePgUpandPgDnkeys,iftheyaresupported.Else,tomovebackwardsbyonepagethe⁁b(pressCntrlandbatthesametime)andtomoveonepageforwardthen⁁f.A⁁uand⁁dallowsthescreentobescrolledupordown,respectively.
•Goingtoaline.Inmanysituationstheuserrequirestogotoaspecificlinenumber(especiallywhencompilingaprogram).Todothisthe‘G’characterisfollowedbythelinenumber.Forexample,‘G’1234goestolinenumber1234.
37.2.7SearchingForStringsThe‘’and‘?’charactersareusedtofindastring.A‘’searchesforwardsforthenextoccurrenceofastring,whereas,‘?’searchesbackfortheoccurrenceofthestring.Thus:
37.2.8GettingOutOfTheEditorAndSavingThere are various options that can be used (depending on what you require).ThesearespecifiedinTable37.4.Theuser’schangesarenotstoredto thefileuntil theuseruseseither‘Z’‘Z’, ‘:’‘w’‘q’or’:’‘w’.Thesediffer in that the‘:’‘w’‘q’and‘Z’‘Z’sequencecausesthechangestobesavedtothefileandquitfromtheeditor,whereas‘:’‘w’saveschangesandtheeditorstaysactive.
Table37.4Methodsofexiting
Option Description
ZZ Exitsfromeditorandsavesallchanges.
:wq<CR> Sameasabove(writeandquit).
:w<CR> Writechangesbutdonotquit.
:wfilename<CR> Writechangestofilename,noquit.
:qexcl<CR> Quitfromeditor,nochanges.
:eexcl<CR> Re-edit,discardingchanges.
Ausercanabandon thechanges thathavebeenmadesince the last savebyusingeither‘:’‘q’‘!’or‘:’‘e’‘!’.Notethat<CR>standsforpressingthereturnkey.
37.2.9Reading-InAndWriting-ToFilesThecommandtoread-infilesis:rfilenameandthecommandtowritethefiletoaspecifiedfile is :w filename.Forexample, :rfred readsinafilecalledfredand:wfred2.txtwritestoafilecalledfred2.txt.
37.2.10UsefulAdvancedEditingFacilitiesTherearemanypowerfultexteditingfacilitiesavailable,someusefulexamplesare:
thischangesalloccurrencesofname1toname2for10lines:
writeslines5to18tofilecalledfred.txt.
37.3ExampleoftexteditingThissectioncontainsapracticalexampleoftextediting.Starttheeditorwith:
thenwhen theeditorhas startedenter ‘i’ toput theeditor into insertmode.Enterthetextgivenbelowandmakethechangesrequired.Ifmistakesaremadeas the text is being typed-in then the back-space keywill delete the previouscharacter,elsewaituntilallthetexthasbeenenteredandthenmaketherequiredmodifications.Thetextis:
Oncethetexthasbeenenteredthenmakethefollowingchanges/operations:(a)Changeloininthetitletolion.Thiscanbedoneinanumberofways,such
as:•MovecursortotheLofLOINpress4×(orxxxx)andthenpressito
enterinsertmodeandentercorrectwordLION.PressESCbuttontoexitfrominsertmode.
•MovecursortotheLofLOINpress4s(substitute4letters)the$signshowstheendofthewordtobesubstituted.Youwillbeininsertmodeautomatically.EnternewtextLIONandpressESCtoreturntonormalmode;
•MovecursortotheLofLIONpressR(overwritemodeandreplace)thiswillautomaticallyputyouintoinsertmode.NextentercorrectLIONandpressESC.
•Foradvancededitinggotostartoftextthentype::s/LOIN/LION/g100<CR>.ThissubstitutesgloballyLOINforLIONfor100lines.
(b)Copythefirst4linesofthesecondparagraphandputtheseafterthe
thirdparagraph.Todothisfirstyank(togetlines)andtheput.First,positionthecursoratanypositiononthelinewhichbeginsthesecondparagraph.Next,getthelinesbyusing4yy(whichgets4linesoruse4Y)thenmovethecursortothelastlineandpressρtoputthelinesbelowlastline.
(c)Deletethesenewlines.Thiscanbedonebymovingthecursortothefirstlineofthenewlinesandthenusing4dd(ordddd)todeletethese4newlines.
(d)Searchforthewordsheepsandchangethistoheaps.Tofindthewordsheepsuse/sheeps<CR>,theeditorwillthenfindthefirstoccurrenceafterthecurrentcursorposition.Ifthewordliesbackwardsfromthecursorthenuse?sheeps<CR>.Oncefoundreplaceitwithheaps.
(e)Searchforthewordstumbled.Howmanyoccurrencesarethere?(f)Writemodifiedtexttothefilelion2.txt.Thisisdonebyusing:w
lion2.txt<CR>.(g)Readthisfileinattheendofthefile.Movethecursortotheendoffile
thenuse:rlion2.txt.Thiswillreadthefilein.(h)Deletethesenewlines.Positionthecursoronthefirstnewlinethenusedd
todeletealine.Repeatthisdeletionwiththerepeatoptionuntilalltherequiredlinesaredeleted.
(i)Findthewordconfusionandchangeittounconfusion,thenundothispressu(theundooption).
(j)Savethetext.Use:wq<CR>.
37.4sededitorThe sed is a non-iterative stream editor. It is useful for editing large files andperformingglobaledits.Thefollowingtextcanbeenteredandoperatedonintheexamplesgiven;callthefileWalrus.
37.4.1GlobalChangingTogloballychangestring1tostring2thefollowingisused:
Forexample,ifweusetheexamplegivenpreviouslytochangehistoher,thefollowingcanbeused:
Wecanseethatonthefifthlinethishasbeenreplacebyther.Toundothisthefollowingcouldbeused:
37.5grepThegrep command searches throughgiven files for a given stringpattern. Itsstandardformatis:
wheretheoptionswhichcanbeusedare:
–v printlinesthatdonotmatch
–v printlinesthatdonotmatch
–X displayonlylinesthatmatchexactly
–c displaycountofmatchinglines
–i ignorecase
Examplesare:
Thegrepistypicallyusedwithapipetosearchtheoutputfromacommand.Forexample, to findeveryoccurrenceof theword set in themanualon theCshell:
whichisequivalentto:
37.6sortThesortutilitysortslinesinthegivenfilesandwritestheoutputtothestandardoutput. It always uses the characters to sort the text and ignores the values ofnumericalvalues.Thestandardformatis:
Asanexample,createthefollowingfileandcallitleague.Itsfunctionisto
list a number of individuals, the number of games they have played and thenumberofpointsscored.Eachfieldisseparatedbyspacesortabs.
To sort the first field, that is the first name, then the sort is used with nooptions.
Next, thesurnamescanbesortedbyaddingthe+1option,whichcauses thesorttoskiptothefirstfield.
ThisisanincorrectsortasSimonRiponcomesbeforeBertRipon.Thereasonthatithasnotsortedthesenamesproperlyisthatithastestedonlythesurname.Totestthefirstfieldafterthesecondthe–2optionisadded.Thusthesort+1–2leaguecommandis interpretedas ‘skip thefirst fieldand thensortbutstopsortingafterthesecondfieldandgobacktothestartoftheline’.
Tosortthethirdfield(thatis,thegamesplayed)thenthe+2noptionisused.Thus sort +2n +1 League is interpreted as ‘skip two fields then sortnumerically,thentheyaresortedbyskippingthefirstfield’.
Tosortinreversetheroptionisused.
Tosortwiththefourthfield(thatis,points):
37.7Exercises37.7.1.Writeacommandusing1s,|andthegrepthatwilldetermineallfiles,in
thecurrentworkingdirectory,whichcontaintheletterr.37.7.2.Usingwho,|andgrep,determinealltheusersonteletypeterminals(that
is,ttyxx).37.7.3.Usingthels-alandgrep,showanyfilewhichhastheattributesrwx-r–
r–.37.7.4.Determineanyusageofthestring“>>”inthemanualoncshandsh.37.7.5.Thefollowingarelistsofteamsandtheirgamesplayed,goalsfor,goals
againstandpoints.Usingthesortutility,determine:(i)Thelistalphabeticallyofteams.
(ii)Theteamssortedbydecendinggoalsfor.(iii)Theteamssortedbyascendinggoalsagainst.(iv)Theteamssortedbypointsthenbygoalsfor.
37.7.6.Usingsortandls–al,listthefilesinthecurrentdirectoryinorderofdecreasingsize.
38
Csh(CShell)
38.1Introduction
The C shell (csh) is one of the interfaces between the user and the UNIXoperatingsystem;othersinclude:•Bourneshell(sh).•Korneshell(ksh).The C shell includes a command interpreter and a high-level programming
language.IthasseveraladvantagesovertheBourneshell,theseinclude:•Variablesaremoreversatile.•Itsupportsarraysofnumbersandstrings.•Improvedprotectionoveraccidentallogout.•Improvedprotectionoveraccidentalfileoverwrite.•Aliasmechanism.•Historymechanismtorecallpastevents.
38.2EnteringtheCShellTheBourneshelland theCshellcanbeusedatany timebutonlyonecanbeusedatatime.Tocall-uptheCshell:
andtheBourneshelliscalled-upusingsh.Normally,theshellatwhichauserisputintoinitiallyissetupintheetcpasswdfile.Thisfilecanonlybechangebythesystemadministrator.Tolistthepasswdfile:
this gives a paged list and the shells are given defined by either binsh orbincsh.Anexcerptfromapasswdfileisgivennext:
In this case, the passwd file has 3 users defined, these are root, fred andfred2. The encrypted password is given in the second field (between the firstandsecondcolon).The third field isauniquenumber thatdefines theuser (inthis case fred is 2 and fred2 is 3). The fourth field, in this case defines thegroup number. The fifth field is simply a comment field and, in this case,containstheuser’snames.Inthenextfieldtheuser’shomedirectoryisdefinedandthefinalfieldcontainstheinitialUNIXshell(inthiscaseitistheCshell).WhenenteringtheCshellthe.cshrcfileisexecuted.ThisfilesetsuptheC
shelltotheneedsoftheuserandisfoundintheuser’shomedirectory.Itcanbefoundbytyping1s–a1intheuser’shomedirectory.Itcanbelistedasfollows:
The.cshrcfilewillbediscussedlater.
38.3LeavingtheCshellAn annoying feature of the Bourne shell is that if the user presses theCONTROL-Dkeystrokebymistakethentheywillbelogged-out.IntheCshellif theignoreeof variable is set then theCONTROL-D (^D) logoutprocess isinactive.AusercanexitfromtheCshellbytypingexit.Tosettheignoreeofvariablejusttype:
This is usually done automatically when entering the shell. An example ofenteringandleavingtheCshellisgivenbelow.
Note:Iftheignoreeofvariableisnotsetthen^DwillexittheCshell.
38.4HistoryThehistorymechanismmaintains a list ofprevious command lines,whicharealso called events. To set the number of events the set history command isused.Forexample,tosetthenumberofstoredeventsto10:
andtorecallthepreviouseventsthehistorycommandistyped:
38.5ReexecutingeventsItispossibletoreexecuteanyeventinthehistorylist.Thereferencetoaneventismadebystartingthelinewitha!.
38.5.1EventNumbersAn event can be reexecuted using the event number. This is achieved by a !followedbytheeventnumber.
Anegativenumberaftertheexclamationmarkreferstoaneventpriortothecurrentevent.
38.5.2ReexecutingPreviousEventTwo exclamation marks (! !) are used to reexecute the previous event. Forexample:
38.5.3EventsUsingTextToexecuteapreviouseventwithtextthenanexclamationmarkfollowedbytextatthebeginningoftheeventcanbeused.Forexample:
38.5.4ChangingLastEventTypicallyausermakesamistakeinacommandlineandwantstoreplaceapartof thecommand linewithanother.Tochangea stringof text in the last eventthen the caret (^) symbol is used. For example ^fred^temp reexecutes the lasteventbutchangesfredfortemp.Forexample:
38.5.5ChangingPreviousEventsTomodify a previous event it is possible to use the :s/old/new to change agiven event. The event is specified by the methods given previously. Forexample:
Thefirstexamplechangesevent13butsubstitutestempforfred.Thesecondexampleexecutesthelasteventbeginningwithcatandsubstitutesyyyforxxx.
38.6Alias
Thealiasmechanismallowsauser tosubstituteagivencommandfora singleword(oralias).Thefollowingarecommonaliases:
Thefirstexampleexecutesthehistorycommandwheneverhisenteredatthecommandline.Thesecondexecutesan1s–a1whendirisentered.Theusercanlistthecurrentlydefinedaliasesbysimplytypingalias,suchas:
Theunaliascommandisusedtoremoveanalias,suchas:
38.7VariablesTheCshellonlyusesstringsanddoesnotusenumbers.Thus,forexample,5isinterpretedas thecharacter5andnotas thenumber5.Tooperateonnumbersthe@isused.
38.7.1VariableSubstitutionThecommandsthatareusedtomanipulatevariablesare:•setenvwhichoperatesonglobalvariables(thatis,systemvariables).•[email protected] variable is recognized by a preceding $ followed by the variable name.
Examplesare$fruit,$numbers,andsoon.
38.7.2StringVariablesTheCshelltreatsvariablesasstrings.Todeclareavariablethesetcommandisused.Forexample:
Thiswilldeclarethevariablemynamewhichcontainsthestring“Bill”.Notethataspaceoneithersideofthe=isnecessary.
38.7.3ArraysOfStringsBefore an arraymember is used itmust be declared, that is, set. It is used todeclareeverymemberofthearray.
38.7.4NumericalVariablesThe@ command is used to assign a numeric variable. The format of the@commandis:@variable-nameoperatorexpressionTheoperatorcanbeanyoftheCoperators.Theseare:
Shiftoperators:
Relationship:
Bitwise:
Logical:
Anexampleisgivennext:
38.7.5FilesFilescanbetestedfortheirstatususingthe–noption,thestandardformis:
wherencanbe:d.fileisadirectorye.fileexistsf.fileisaplainfileo.userownsthefiler.userhasreadaccesstofilew.userhaswriteaccesstofilex.userhasexecuteaccesstofilez.fileisempty
Forexample
38.8Specialforms($#,$?and~)The number of elements in an array is determined using the $# operator. Thegeneralformatis:
Todetermineifavariablehasbeendeclaredthe$?canbeused.Thegeneralformatis:
Thevaluereturnedwillbezeroifithasnotbeendeclaredand1ifithasbeendeclared.
The~ (tilde) operator is used to substitute for the full pathname of a givenuser.Forexample:
Thus–fredstandsforuserfred’shomedirectory,andsoon.
38.9ShellvariablesThesevariables canbe set by either the shell or theuser.There are twobasictypes:thefirstisgivenvalues,whereasthesecondiseithersetorunset.
38.9.1SystemVariablesThatTakeAValueThestandardvariablesthattakeonvaluesare:•$argv–Theargvvariablecontainsallthecommandlinearguments.argv
[0]holdsthenameofthecallingprogram,argv[1]containsthefirstargument,andsoon.Forexample,ifthecommandlineis:
Thentheargvvariableswillbe:
•$#argv–containsthenumberofcommandlinearguments.Inthepreviousexamplethiswillbe4.
•$cdpath–Thevariableisusedbythecdcommand.Whenacdcommandwithasimplefilenameisgiven,thenthesystemwillsearchthecurrentworkingdirectory.Ifthefileisnotinthecurrentworkingdirectorythenthesystemwillsearchinthedirectoriesgivenbythecdpathvariable.Ifafileisfoundinanyofthesearchpathsthenthesystemchangestothatdirectory.Itisusuallysetinthe.loginfile,forexample:
•$cwd–fullpathnameofcurrentdirectory.•$history–definesthesizeofthehistorylist.Thisvalueisusuallysetinthe
.cshrcfile,suchas:
•$home–definesthehomedirectoryoftheuser.
•$mail–fileswheretheshellchecksformail.•$path–givesthedirectoriesinwhichthesystemsearchesforexecutables.
Usuallythesearchpathis‘.’,‘/bin’andusr/bin’.Forexample:
•$prompt–Astringthatisprintedbeforeeachcommandisread.Ifa‘!’appearsinthestringthecurrenteventnumberissubstituted.Thedefaultpromptisa%.Anexamplepromptsettingis:
whichwillprintasaprompt:
ifthecurrentdirectoryisusrstaff/bill_b/docs,thecurrenteventwas15andtheuser’snameisbill_b.
•$savehist–containsthenumberofhistoryeventsthatarestoredwhentheuserlogsout.Theseeventsarestoredinthe~/.historyfile.Whentheusernextlogsinthenthecurrenthistorylistwillbeasthesavedeventhistory.
38.9.2SystemVariablesAreSetThestandardvariablesthataresetare:•$filec–enablesfilenamecompletion.Ifitissetthenthefilenameis
completedwhenthe<ESC>keyispressedandthefileisfound.
maybecome:
The<Cntl-D>(^D)characterisusedtolistanyfileswhichmatchthecurrentinput.Forexample:
InthisexamplethefileswhichmatchthefirstthreecharactersFORarelisted.
•$ignoreeof–ifsettheshellignoresthe<Cntrl-D>logoutcommandandexitisusedtoleavetheshell.Itissetwith:
•$noclobber–whensettherearerestrictionsontheredirectiontofiles.Ifa>isgivenandthefileexistsitwillnotbedestroyed.
38.10ShellscriptsA shell script is a file that contains C shell commands. To execute a file themodemustbechangedsothatitcanbeexecuted.Forexample:
NotethatthefirstnonblankcharacterinaCshellscriptmustbea#.ThistellstheshellthatitisaCshellscript.
38.11ControlStructuresTheCshellcontrolstatementsareif,foreach,whileandswitch.
38.11.1IfThegeneralformatoftheifcontrolstructureisgivenbelow.
AnexampleofaCshellscriptusingtheifcontrolstructureis:
Ifthescript’sfilenamewereargtestthenatypicalrunsessionmaybe:
38.11.2If-ThenElseTherearethreedifferenttypesofif-thenelsestructures:
Type1 Type2 Type3
if(expression)thencommands if(expression)thencommands if(expression)thencommands
endif elsecommands elseif(expression)then.
endif .
endif
AnexampleofaShellscriptusingif-thenis:
Ifthefileiscalledgradethenatypicalrunsessionmaybe:
38.11.3ForeachThe foreach structure reads each argument of an argument list in turn. Thestandardformatisasfollows:
Whentheloopisfirstexecutedthenloopindexwillbeassignedthefirstvalueintheargument-list.Thecommandsarethenexecutedandtheloopreturnstothestartandtheloopindexthentakesonthesecondvalueintheargument-list,andsoon.
38.11.4WhileThegeneralformatofthewhileloopis:
The followingshell script isanexamplewhichdetermines the factorialofanumber.
38.11.5SwitchTheswitchstatementcanchoosebetweenseveraldifferentstrings.Thegeneralformatis:
An example of the switch structure which implements a basic calculator isgivennext:
38.12AutomaticallyexecutedCshellscripts(.login.cshrc)Whensomeonelogsontothesystem,orstartsaCshell,threeCshellscriptsarerunatvarioustimes.
38.12.1The.LoginFileThe.loginfileisexecutedwhentheuserlogsontothesystem.Usuallythisfilecontainsterminalandkeyboardcommands.Anexampleofatypical.loginfileisshownbelow.Inthiscase,thesetenvcommandisusedtosetavariableforallshells,thatiscshandsh.Theterminaltypesetupisavt100.
38.12.2The.CshrcFileThe.cshrcfileisexecutedwheneveraCshell isrun.Againit isfoundinthehomedirectoryoftheuser.ItistypicallyusedtosetupparametersusedbytheCshell,suchasthepath,prompt,andsoon.Aquickwayoflistingthe.cshrcfilewhereveryouareis:
Atypical.cshrcfileis:
38.12.3The.LogoutFileThe.logoutfileisautomaticallyexecutedwhentheuserlogsoutofthesystem.It typicallycontainscommandswhich tidyup theuser’sworkareaandalso towritemessages.
38.13Exercises38.13.1.Usinganalias,defineacommandnamedrenamewhichisequivalentto:
38.13.2.Usingthedatecommand,setuserprompttogivethedate.38.13.3.WriteaCshellscriptthatcalculatesthesumofnumbersup-toand
includingthenumbergiven.38.13.4.WriteaCshellscriptnamedadd_dot_C.whichwilladda.ctoany
givenfilename.Forexample:
wouldcausethefilefredtobecomefred.c.38.13.5.Thecommandforfindingagivenfileonthesystemis:
whichsearchesfromthetop-leveldirectoryforthefilecalledfilename.Forexample,tofindprog1.cthefollowingcanbeused:
WriteaCshellscriptwhichiscalledfindfileinwhichtheargumentpassedtoitisthefilename.Forexample,
38.13.6.Thestreameditorsedcanbeusedtoreplaceagivenwordwithanotherword.Theformatofthiscommandisgivenbelow:
Thischangeswordoldforwordnewgloballyinfilecalledfilename.Writeashellscriptcalledreplacewhichgivesthreearguments.Thefirsttwoareforthewordsandthethirdforthefilename.Forexample,toreplacefredforterryinthefilename_file:
38.13.7.WriteaCshellscriptwhichwillgiveinformationaboutagivenfile.Theinformationshouldincludeaccessrights,whetheritisofzerolength,filetype,andsoon.Nametheshellscripttestfile.
A
JavaClassesjava/java/lang/java/lang/Object.classjava/lang/Exception.classjava/lang/Integer.classjava/lang/NumberFormatException.class java/lang/Throwable.class
java/lang/Class.classjava/lang/IllegalAccessException.class java/lang/StringBuffer.class
java/lang/ClassNotFoundException.classjava/lang/IllegalArgumentException.classjava/lang/Number.classjava/lang/InterruptedException.classjava/lang/String.classjava/lang/RuntimeException.class java/lang/InternalError.class
java/lang/Long.classjava/lang/Character.class java/lang/CloneNotSupportedException.class
java/lang/InstantiationException.class java/lang/VirtualMachineError.classjava/lang/Double.classjava/lang/Error.classjava/lang/NullPointerException.class java/lang/Cloneable.class
java/lang/System.classjava/lang/ClassLoader.classjava/lang/Math.classjava/lang/Float.classjava/lang/Runtime.classjava/lang/StringIndexOutOfBoundsException.class
java/lang/IndexOutOfBoundsException.class java/lang/SecurityException.classjava/lang/LinkageError.classjava/lang/Runnable.classjava/lang/Process.classjava/lang/SecurityManager.classjava/lang/Thread.classjava/lang/UnsatisfiedLinkError.class
java/lang/IncompatibleClassChangeError.classjava/lang/NoSuchMethodError.class java/lang/IllegalThreadStateException.classjava/lang/ThreadGroup.class java/lang/ThreadDeath.classjava/lang/ArraylndexOutOfBoundsException.classjava/lang/Boolean.class
java/lang/Compiler.class java/lang/NoSuchMethodException.classjava/lang/ArithmeticException.class java/lang/ArrayStoreException.classjava/lang/ClassCastException.class java/lang/NegativeArraySizeException.classjava/lang/IllegalMonitorStateException.classjava/lang/ClassCircularityError.class java/lang/ClassFormatError.classjava/lang/AbstractMethodError.class java/lang/IllegalAccessError.classjava/lang/InstantiationError.class java/lang/NoSuchFieldError.classjava/lang/NoClassDefFoundError.class java/lang/VerifyError.classjava/lang/OutOfMemoryError.class java/lang/StackOverflowError.classjava/lang/UnknownError.classjava/lang/Win32Process.classjava/io/java/io/FilterOutputStream.class java/io/OutputStream.class
java/io/IOException.classjava/io/PrintStream.classjava/io/FileInputStream.classjava/ioAnterruptedIOException.classjava/io/File.classjava/io/InputStream.class java/io/BufferedInputStream.class
java/io/FileOutputStream.class java/io/FileNotFoundException.classjava/io/BufferedOutputStream.class java/io/FileDescriptor.classjava/io/FilenameFilter.class java/io/FilterInputStream.classjava/io/PipedInputStream.class java/io/PipedOutputStream.classjava/io/EOFException.class java/io/UTFDataFormatException.classjava/io/DataInput.classjava/io/DataOutput.class java/io/DataInputStream.class
java/io/PushbackInputStream.class java/io/ByteArrayInputStream.classjava/io/SequenceInputStream.class java/io/StringBufferInputStream.classjava/io/LineNumberInputStream.class java/io/DataOutputStream.classjava/io/ByteArrayOutputStream.class java/io/RandomAccessFile.classjava/io/StreamTokenizer.classjava/util/java/util/Hashtable.class java/util/Enumeration.class
java/util/HashtableEnumerator.class java/util/Properties.classjava/util/HashtableEntry.classjava/util/Dictionary.classjava/util/Date.classjava/util/NoSuchElementException.class java/util/StringTokenizer.class
java/util/Random.classjava/util/VectorEnumerator.classjava/util/Vector.classjava/util/BitSet.classjava/util/EmptyStackException.class java/util/Observable.class
java/util/Observer.classjava/util/ObserverList.classjava/util/Stack.classjava/awt/java/awt/Toolkit.class
java/awt/peer/java/awt/peer/WindowPeer.class java/awt/peer/TextFieldPeer.class
java/awt/peer/ContainerPeer.class java/awt/peer/PanelPeer.classjava/awt/peer/CanvasPeer.class java/awt/peer/FramePeer.classjava/awt/peer/ChoicePeer.class java/awt/peer/CheckboxMenuItemPeer.classjava/awt/peer/TextAreaPeer.class java/awt/peer/FileDialogPeer.classjava/awt/peer/TextComponentPeer.class java/awt/peer/ScrollbarPeer.classjava/awt/peer/ButtonPeer.class java/awt/peer/ComponentPeer.classjava/awt/peer/MenuComponentPeer.class java/awt/peer/MenuItemPeer.classjava/awt/peer/CheckboxPeer.class java/awt/peer/MenuPeer.classjava/awt/peer/ListPeer.class java/awt/peer/MenuBarPeer.classjava/awt/peer/LabelPeer.class java/awt/peer/DialogPeer.classjava/awt/Image.classjava/awt/MenuItem.classjava/awt/MenuComponent.classjava/awt/image/java/awt/image/ImageProducer.class java/awt/image/ColorModel.class
java/awt/image/DirectColorModel.class java/awt/image/ImageConsumer.classjava/awt/image/ImageObserver.class java/awt/image/CropImageFilter.classjava/awt/image/ImageFilter.class java/awt/image/FilteredImageSource.classjava/awt/image/IndexColorModel.classjava/awt/image/MemoryImageSource.class java/awt/image/PixelGrabber.classjava/awt/image/RGBImageFilter.class java/awt/FontMetrics.classjava/awt/Checkbox.class java/awt/CheckboxGroup.classjava/awt/MenuContainer.classjava/awt/Menu.classjava/awt/Insets.classjava/awt/MenuBar.classjava/awt/List.classjava/awt/Label.classjava/awt/Component.class java/awt/TextField.class
java/awt/TextComponent.classjava/awt/Dialog.classjava/awt/Font.classjava/awt/Window.classjava/awt/FocusManager.classjava/awt/Panel.classjava/awt/Container.class java/awt/Graphics.class
java/awt/CheckboxMenuItem.classjava/awt/Canvas.classjava/awt/Frame.classjava/awt/Choice.classjava/awt/Event.class
java/awt/TextArea.classjava/awt/AWTError.classjava/awt/Polygon.classjava/awt/FlowLayout.classjava/awt/Point.classjava/awt/FileDialog.class java/awt/Scrollbar.class java/awt/Dimension.class
java/awt/Color.classjava/awt/Button.classjava/awt/LayoutManager.class java/awt/Rectangle.class
java/awt/BorderLayout.class java/awt/GridLayout.classjava/awt/GridBagConstraints.class java/awt/GridBagLayout.classjava/awt/GridBagLayoutInfo.class java/awt/CardLayout.classjava/awt/MediaTracker.class java/awt/MediaEntry.classjava/awt/ImageMediaEntry.classjava/awt/AWTException.classjava/net/java/net/URL.classjava/net/URLStreamHandlerFactory.class java/net/InetAddress.class
java/net/UnknownContentHandler.class java/net/UnknownHostException.classjava/net/URLStreamHandler.class java/net/URLConnection.classjava/net/MalformedURLException.class java/net/ContentHandlerFactory.classjava/net/ContentHandler.class java/net/UnknownServiceException.classjava/net/ServerSocket.class java/net/PlainSocketImpl.classjava/net/SocketImpl.class java/net/ProtocolException.classjava/net/SocketException.class java/net/SocketInputStream.classjava/net/Socket.classjava/net/SocketImplFactory.class java/net/SocketOutputStream.class
java/net/DatagramPacket.class java/net/DatagramSocket.classjava/net/URLEncoder.classjava/applet/java/applet/Applet.class java/applet/AppletContext.class
java/applet/AudioClip.classjava/applet/AppletStub.classsun/sun/tools/sun/tools/debug/sun/tools/debug/BreakpointQueue.class
sun/tools/debug/DebuggerCallback.class sun/tools/debug/RemoteThread.classsun/tools/debug/StackFrame.class sun/tools/debug/RemoteAgent.classsun/tools/debug/AgentConstants.class sun/tools/debug/AgentIn.classsun/tools/debug/RemoteObject.classsun/tools/debug/RemoteStackVariable.classsun/tools/debug/Remote Value.class sun/tools/debug/RemoteClass.classsun/tools/debug/Agent.class sun/tools/debug/RemoteBoolean.classsun/tools/debug/RemoteChar.class sun/tools/debug/RemoteString.classsun/tools/debug/NoSessionException.class sun/tools/debug/Field.class
sun/tools/debug/NoSuchLineNumberException.classsun/tools/debug/RemoteShort.class sun/tools/debug/RemoteThreadGroup.classsun/tools/debug/RemoteInt.class sun/tools/debug/ResponseStream.classsun/tools/debug/RemoteDouble.class sun/tools/debug/LocalVariable.classsun/tools/debug/BreakpointSet.class sun/tools/debug/RemoteStackFrame.classsun/tools/debug/MainThread.class sun/tools/debug/BreakpointHandler.classsun/tools/debug/AgentOutputStream.class sun/tools/debug/RemoteLong.classsun/tools/debug/RemoteFloat.class sun/tools/debug/RemoteArray.classsun/tools/debug/InvalidPCException.class sun/tools/debug/LineNumber.classsun/tools/debug/RemoteField.class sun/tools/debug/NoSuchFieldException.classsun/tools/debug/RemoteByte.class sun/tools/debug/EmptyApp.classsun/tools/debug/RemoteDebugger.classsun/tools/java/sun/tools/java/RuntimeConstants.class sun/tools/java/Constants.class
sun/tools/java/Environment.class sun/tools/java/ClassPath.classsun/tools/java/ClassDeclaration.class sun/tools/java/FieldDefinition.classsun/tools/java/Type.class sun/tools/java/ClassNotFound.classsun/tools/java/ClassType.class sun/tools/java/ClassDefinition.classsun/tools/java/Parser.class sun/tools/java/ClassPathEntry.classsun/tools/java/CompilerError.class sun/tools/java/Identifier.classsun/tools/java/Package.class sun/tools/java/ClassFile.classsun/tools/java/Imports.class sun/tools/java/ArrayType.classsun/tools/java/AmbiguousField.class sun/tools/java/MethodType.classsun/tools/java/Scanner.class sun/tools/java/SyntaxError.classsun/tools/java/BinaryClass.class sun/tools/java/BinaryField.classsun/tools/java/AmbiguousClass.class sun/tools/java/BinaryConstantPool.classsun/tools/java/ScannerInputStream.class sun/tools/java/BinaryAttribute.classsun/tools/java/BinaryCode.class sun/tools/java/BinaryExceptionHandler.classsun/tools/javac/sun/tools/javac/Main.class sun/tools/javac/SourceClass.class
sun/tools/javac/CompilerField.class sun/tools/javac/SourceField.classsun/tools/javac/BatchEnvironment.class sun/tools/javac/ErrorConsumer.classsun/tools/javac/ErrorMessage.class sun/tools/javac/BatchParser.classsun/tools/zip/sun/tools/zip/ZipFile.class sun/tools/zip/ZipEntry.class
sun/tools/zip/ZipFileInputStream.class sun/tools/zip/ZipConstants.classsun/tools/zip/ZipFormatException.classsun/tools/zip/ZipReaderInputStream.class sun/tools/zip/ZipReader.class
sun/tools/tree/sun/tools/tree/ConstantExpression.class sun/tools/tree/LocalField.class
sun/tools/tree/Expression.class sun/tools/tree/IncDecExpression.classsun/tools/tree/SuperExpression.class sun/tools/tree/NaryExpression.classsun/tools/tree/StringExpression.class sun/tools/tree/UnaryExpression.classsun/tools/tree/Context.class sun/tools/tree/ExpressionStatement.classsun/tools/tree/ConditionVars.class sun/tools/tree/Node.classsun/tools/tree/CharExpression.class sun/tools/tree/CaseStatement.classsun/tools/tree/LessExpression.class sun/tools/tree/IntegerExpression.classsun/tools/tree/SubtractExpression.classsun/tools/tree/ArrayAccessExpression.class sun/tools/tree/TryStatement.classsun/tools/tree/BinaryEqualityExpression.class sun/tools/tree/Statement.classsun/tools/tree/AssignSubtractExpression.classsun/tools/tree/FinallyStatement.class sun/tools/tree/ForStatement.classsun/tools/tree/DivRemExpression.class sun/tools/tree/BinaryExpression.classsun/tools/tree/ShiftRightExpression.classsun/tools/tree/AssignMultiplyExpression.classsun/tools/tree/BooleanExpression.classsun/tools/tree/BinaiyAritnmeticExpression.classsun/tools/tree/ThrowStatement.classsun/tools/tree/AssignDivideExpression.classsun/tools/tree/AssignShiftLeftExpression.classsun/tools/tree/NewArrayExpression.class sun/tools/tree/AndExpression.classsun/tools/tree/AssignBitOrExpression.class sun/tools/tree/BreakStatement.classsun/tools/tree/SynchronizedStatement.classsun/tools/tree/PreDecExpression.class sun/tools/tree/CompoundStatement.classsun/tools/tree/DoubleExpression.class sun/tools/tree/ConvertExpression.classsun/tools/tree/NullExpression.class sun/tools/tree/LessOrEqualExpression.classsun/tools/tree/IdentifierExpression.class sun/tools/tree/ReturnStatement.classsun/tools/tree/BitNotExpression.class sun/tools/tree/LongExpression.classsun/tools/tree/VarDeclarationStatement.classsun/tools/tree/MethodExpression.class sun/tools/tree/ThisExpression.classsun/tools/tree/BitOrExpression.class sun/tools/tree/PositiveExpression.classsun/tools/tree/IfStatement.class sun/tools/tree/FloatExpression.classsun/tools/tree/NotEqualExpression.classsun/tools/tree/InstanceOfExpression.class sun/tools/tree/NotExpression.classsun/tools/tree/BitAndExpression.class sun/tools/tree/DivideExpression.class
sun/tools/tree/ShortExpression.class sun/tools/tree/RemainderExpression.classsun/tools/tree/NewInstanceExpression.class sun/tools/tree/SwitchStatement.classsun/tools/tree/AddExpression.class sun/tools/tree/AssignOpExpression.classsun/tools/tree/EqualExpression.class sun/tools/tree/PostIncExpression.classsun/tools/tree/GreaterExpression.class sun/tools/tree/PostDecExpression.classsun/tools/tree/AssignExpression.class sun/tools/tree/WhileStatement.classsun/tools/tree/ContinueStatement.classsun/tools/tree/ConditionalExpression.classsun/tools/tree/AssignAddExpression.classsun/tools/tree/BinaryBitExpression.class sun/tools/tree/CastExpression.classsun/tools/tree/AssignBitXorExpression.classsun/tools/tree/ArrayExpression.classsun/tools/tree/InlineMethodExpression.classsun/tools/tree/InlineNewInstanceExpression.classsun/tools/tree/CodeContext.classsun/tools/tree/AssignShiftRightExpression.classsun/tools/tree/UnsignedShiftRightExpression.classsun/tools/tree/AssignBitAndExpression.classsun/tools/tree/ShiftLeftExpression.class sun/tools/tree/CatchStatement.classsun/tools/tree/IntExpression.class sun/tools/tree/TypeExpression.classsun/tools/tree/CommaExpression.classsun/tools/tree/AssignUnsignedShiftRightExpression.classsun/tools/tree/ExprExpression.classsun/tools/tree/AssignRemainderExpression.classsun/tools/tree/ByteExpression.class sun/tools/tree/BinaryAssignExpression.classsun/tools/tree/DoStatement.class sun/tools/tree/DeclarationStatement.classsun/tools/tree/MultiplyExpression.classsun/tools/tree/InlineReturnStatement.class sun/tools/tree/BitXorExpression.classsun/tools/tree/BinaryCompareExpression.classsun/tools/tree/BinaryShiftExpression.class sun/tools/tree/CheckContext.classsun/tools/tree/PreIncExpression.classsun/tools/tree/GreaterOrEqualExpression.classsun/tools/tree/FieldExpression.class sun/tools/tree/OrExpression.classsun/tools/tree/BinaryLogicalExpression.classsun/tools/tree/NegativeExpression.class sun/tools/tree/LengthExpression.classsun/tools/asm/sun/tools/asm/Assembler.class sun/tools/asm/Instruction.class
sun/tools/asm/LocalVariable.class sun/tools/asm/ArrayData.classsun/tools/asm/LocalVariableTable.classsun/tools/asm/SwitchDataEnumeration.class sun/tools/asm/ConstantPool.classsun/tools/asm/ConstantPoolData.classsun/tools/asm/NameAndTypeConstantData.classsun/tools/asm/NumberConstantData.classsun/tools/asm/FieldConstantData.classsun/tools/asm/TryData.class sun/tools/asm/Label.classsun/tools/asm/SwitchData.class sun/tools/asm/CatchData.classsun/tools/asm/StringExpressionConstantData.classsun/tools/asm/NameAndTypeData.class sun/tools/asm/StringConstantData.classsun/tools/asm/ClassConstantData.classsun/tools/ttydebug/sun/tools/ttydebug/TTY.classsun/tools/javadoc/sun/tools/javadoc/Main.classsun/tools/javadoc/DocumentationGenerator.class
sun/tools/javadoc/HTMLDocumentationGenerator.classsun/tools/javadoc/MIFDocumentationGenerator.classsun/tools/javadoc/MIFPrintStream.classsun/net/sun/net/MulticastSocket.class sun/net/URLCanonicalizer.class
sun/net/NetworkClient.class sun/net/NetworkServer.classsun/net/ProgressData.class sun/net/ProgressEntry.classsun/net/TelnetInputStream.class sun/net/TelnetProtocolException.classsun/net/TelnetOutputStream.class sun/net/TransferProtocolClient.classsun/net/ftp/sun/net/ftp/FtpInputStream.class sun/net/ftp/FtpClient.class
sun/net/ftp/FtpLoginException.class sun/net/ftp/FtpProtocolException.classsun/net/ftp/IftpClient.classsun/net/nntp/sun/net/nntp/NewsgroupInfo.class sun/net/nntp/NntpClient.class
sun/net/nntp/UnknownNewsgroupException.classsun/net/nntp/NntpProtocolException.class sun/net/nntp/NntpInputStream.classsun/net/smtp/sun/net/smtp/SmtpPrintStream.class sun/net/smtp/SmtpClient.class
sun/net/smtp/SmtpProtocolException.classsun/net/www/sun/net/www/auth/sun/net/www/auth/Authenticator.class sun/net/www/auth/basic.class
sun/net/www/content/sun/net/www/content/text/sun/net/www/content/text/Generic.class sun/net/www/content/text/plain.class
sun/net/www/content/image/
sun/net/www/content/image/gif.class sun/net/www/content/image/jpeg.classsun/net/www/content/image/x_xbitmap.classsun/net/www/content/image/x_xpixmap.classsun/net/www/FormatException.class sun/net/www/MessageHeader.classsun/net/www/MeteredStream.class sun/net/www/ProgressReport.classsun/net/www/MimeEntry.class sun/net/www/MimeLauncher.classsun/net/www/MimeTable.class sun/net/www/URLConnection.classsun/net/www/UnknownContentException.classsun/net/www/UnknownContentHandler.classsun/net/www/protocol/sun/net/www/protocol/file/sun/net/www/protocol/file/Handler.class
sun/net/www/protocol/file/FileURLConnection.classsun/net/www/protocol/http/sun/net/www/protocol/http/Handler.class
sun/net/www/protocol/http/HttpURLConnection.classsun/net/www/protocol/http/HttpPostBufferStream.classsun/net/www/protocol/doc/sun/net/www/protocol/doc/Handler.classsun/net/www/protocol/verbatim/sun/net/www/protocol/verbatim/Handler.class
sun/net/www/protocol/verbatim/VerbatimConnection.classsun/net/www/protocol/gopher/sun/net/www/protocol/gopher/GopherClient.class
sun/net/www/protocol/gopher/GopherInputStream.classsun/net/www/http/sun/net/www/http/UnauthorizedHttpRequestException.class
sun/net/www/http/HttpClient.class sun/net/www/http/AuthenticationInfo.classsun/awt/sun/awt/HorizBagLayout.class sun/awt/VerticalBagLayout.class
sun/awt/VariableGridLayout.class sun/awt/FocusingTextField.classsun/awt/win32/sun/awt/win32/MToolkit.class sun/awt/win32/MMenuBarPeer.class
sun/awt/win32/MButtonPeer.class sun/awt/win32/Win32Image.classsun/awt/win32/MScrollbarPeer.class sun/awt/win32/MDialogPeer.classsun/awt/win32/MCheckboxMenuItemPeer.classsun/awt/win32/Win32Graphics.class sun/awt/win32/MListPeer.classsun/awt/win32/MWindowPeer.class sun/awt/win32/MMenuItemPeer.classsun/awt/win32/ModalThread.class sun/awt/win32/MCanvasPeer.classsun/awt/win32/MFileDialogPeer.class sun/awt/win32/MTextAreaPeer.classsun/awt/win32/MPanelPeer.class sun/awt/win32/MComponentPecr.class
sun/awt/win32/MCheckboxPeer.class sun/awt/win32/MLabelPeer.classsun/awt/win32/Win32FontMetrics.class sun/awt/win32/MFramePeer.classsun/awt/win32/MMenuPeer.class sun/awt/win32/MChoicePeer.classsun/awt/win32/MTextFieldPeer.class sun/awt/win32/Win32PrintJob.classsun/awt/image/sun/awt/image/URLImageSource.class sun/awt/image/ImageWatched.class
sun/awt/image/InputStreamImageSource.classsun/awt/image/ConsumerQueue.class sun/awt/image/ImageDecoder.classsun/awt/image/ImageRepresentation.classsun/awt/image/ImageInfoGrabber.class sun/awt/image/XbmImageDecoder.classsun/awt/image/GifImageDecoder.class sun/awt/image/ImageFetcher.classsun/awt/image/PixelStore.class sun/awt/image/JPEGImageDecoder.classsun/awt/image/PixelStore8.class sun/awt/image/ImageFetchable.classsun/awt/image/OffScreenImageSource.class sun/awt/image/PixelStore32.classsun/awt/image/ImageFormatException.classsun/awt/image/FileImageSource.class sun/awt/image/Image.classsun/awt/UpdateClient.class sun/awt/ScreenUpdaterEntry.classsun/awt/ScreenUpdater.classsun/misc/sun/misc/Ref.classsun/misc/MessageUtils.classsun/misc/Cache.classsun/misc/CacheEntry.class sun/misc/CacheEnumerator.class
sun/misc/CEFormatException.class sun/misc/CEStreamExhausted.classsun/misc/CRC16.classsun/misc/CharacterDecoder.class sun/misc/BASE64Decoder.class
sun/misc/UCDecoder.class sun/misc/UUDecoder.classsun/misc/CharacterEncoder.class sun/misc/BASE64Encoder.classsun/misc/HexDumpEncoder.class sun/misc/UCEncoder.classsun/misc/UUEncoder.class sun/misc/Timeable.classsun/misc/TimerTickThread.classsun/misc/Timer.classsun/misc/TimerThread.class sun/misc/ConditionLock.class
sun/misc/Lock.classsun/audio/sun/audio/AudioDataStream.class sun/audio/AudioData.class
sun/audio/AudioDevice.class sun/audio/AudioPlayer.classsun/audio/AudioStream.class sun/audio/NativeAudioStream.classsun/audio/InvalidAudioFormatException.classsun/audio/AudioTranslatorStream.class sun/audio/AudioStreamSequence.class
sun/audio/ContinuousAudioDataStream.classsun/applet/sun/applet/StdAppletViewerFactory.class sun/applet/TextFrame.class
sun/applet/AppletViewerFactory.class sun/applet/AppletViewer.classsun/applet/AppletCopyright.class sun/applet/AppletAudioClip.classsun/applet/AppletSecurity.class sun/applet/AppletThreadGroup.classsun/applet/AppletClassLoader.class sun/applet/AppletPanel.classsun/applet/AppletViewerPanel.class sun/applet/AppletProps.classsun/applet/AppletSecurityException.classsun/applet/AppletZipClassLoader.class
TurboPascalaccessessomestandardproceduresandfunctionsthroughunits,whicharelibrariesofprecompiledmodules.Forexample,theCrtunitcontainsroutineswhichaccessthetextdisplay.Touseaunittheuseskeywordmustbeincluded in a statement near the top of the program. For example, to use theclrscrfunction:
D
AssemblyLanguageReferenceD.1AssemblylanguagemnemonicsTableD.1 outlines theAssemblyLanguagemnemonics (in column1) and theequivalentencodedbitvalues(incolumn3).Italsoshowsthenumberofcyclesfora8086processoranda80386processor(columns4and5).Theexplanationoftheencodedbitvaluesisgivenafterthetable.
TableD.1AssemblyLanguagereference
Syntax:
reg Ageneral-purposeregisterofanysize.
segreg Asegmentregisters,suchasDS,ES,SSorCS.
accum Anaccumulatorofanysize:ALorAX(orEAXon386/486).
mem Adirectorindirectmemoryoperandofanysize.
label Alabeledmemorylocationinthecodesegment.
src,dest Asourceofdestinationmemoryoperandusedinastringoperand.
immed Aconstantoperand.
andthebitsarespecifiedby:
d directionbit.Ifset(1)thenthetransferisfrommemorytoregisterorregistertoregister,andthedestinationisaregfield.Ifnotsetthenthesourceisaregisterfieldandthetransferisfromregistertomemory.
w word/bytebit.Ifsetthe16-bitoperandsareused,else8-bitoperandsareused.
s signbit.Ifsetthentheoperandhasasign-bit.
mod mode.Identifiestheregister/memorymode.Theseare:
00 Ifr/mis110thendirectmemoryisused,elsethedisplacementis0andanindirectmemoryoperandisused.
01 Anindirectmemoryoperandisusedwithan8-bitdisplacement.
10 Anindirectmemoryoperandisusedwitha16-bitdisplacement.
11 Atwo-registerinstructionisused;theregfieldspecifiesthedestinationandther/mfieldspecifiesthesource.
regregister.Specifiesoneofthegeneral-purposeregisters.Theseare:
reg 16-bit,ifw=1 8-bit,ifw=0
000 AX AL
001 CX CL
010 DX DL
011 BX BL
100 SP AH
100 SP AH
101 BP CH
110 SI DH
111 DI BH
r/mregister/memory.Specifiesamemoryofregisteroperand.Ifthemodfileis11thentheregisterisspecifiedwiththeregfield(asgivenabove),elseithasthefollowingsettings:
reg Operandaddress
000 DS:[BX+SI+disp]
001 DS:[BX+DI+disp]
010 SS:[BP+SI+disp]
011 SS:[BP+DI+disp]
100 DS:[SI+disp]
101 DS:[DI+disp]
110 DS:[BP+disp]
111 DS:[BX+disp]
Theinstructionencodinghastheform:
where:
Disp displacement.Specifiestheoffsetformemoryoperands.
mmedi register/memory.Specifiestheactualvaluesforconstantvalues
D.2AssemblerdirectivesTableD.2outlinessomeAssemblyLanguagedirectives.
TableD.2AssemblyLanguagereference
Directive Description
.386 Enablesassemblyof386code.
.8086 Enablesassemblyof8086code.
ASSUMEsegreg:name Selectssegregtobethedefaultsegmentregisterforallsymbolsinthenamedsegment.
.CODE Definesthecodesegment.
COMMENT Definesacomment.
.CONST Definesaconstant.
nameDBinit Allocationsandoptionallyinitializesabyteofstorageforeachinit.
nameDWinit Allocationsandoptionallyinitializesawordofstorageforeachinit.
nameDDinit Allocationsandoptionallyinitializesadoublewordofstorageforeachinit.
nameDFinit Allocationsandoptionallyinitializesafarword(6bytes)ofstorageforeachinit.
nameDQinit Allocationsandoptionallyinitializesaquadword(8bytes)ofstorageforeachinit.
.DATA Definethedatasegment.
ELSE DefinesanalternativeblockoftheIFdirective.
END Definestheendofamodule.
ENDIF DefinestheendoftheIFdirective.
EXTERNnames Definesoneofmoreexternalvariables,labelsorsystemswhicharecallednames.
IFexpressionifstatements
ENDIF
DefinestheIFdirective.
INCLUDEfilename Includessourcecode.
.MODELmem_model Definesmemorymodel.
namemodule_name Definesthemodulename.
orgexpress Organizestheprograminmemory.
.stacksize Definesthestacksize.
titletext Definestitle.
D.3CandPascalinterruptsIn Turbo/Borland C there are four main functions to interrupt the processor:int86x(),intdos(),intr()andint86().Thesefunctionsareprototypedintheheader file dos.h. This header file also contains a structure definition thatallows aCprogram togain access to theprocessor’s registers.Parameters arepassed into and out of the interrupt sevice routines via these registers. Theformatofthestructureis:
Registers are accessed either as 8-bit registers (such as AL, AH) or 16-bitregisters(suchasAX,BX).Ifastructurenameregsisdeclared,then:
Thesyntaxofthefunctionint86()takestheformof
wherethefirstargumentoftheparameterlististheinterruptnumber,theinputregisters are passed as the second argument and the output registers the third.Parameters arepassed to the interrupt routineby setting certain input registersandparametersarepassedbackfromtheinterruptintheoutputregisters.In a similiarway Turbo Pascal provides access throught the routine named
Intr().Togainaccesstothisproceduretheusesdos;statementisplacednearthetopoftheprogram.AdatatypenamedRegistershasalsobeenpredefined,asshownbelow.Notethatitispossibletouseeitherthe16-bitregisters(suchasAX,BX)or8-bit(suchasAL,AH):
InProgramD.1, theDOS interrupt21h and function02h (writecharacter totheoutput)isusedtodisplaythecharacter‘A’.Inthiscase,thefunctionnumber02hisloadedintoAHandthecharactertobedisplayedisloadedintoDL.
ProgramD.2showshowaprogramcangainaccess to thesystemdate.Thefunctionusedinthisexampleis2Ah.TestrunD.1givesasamplerun.
E
ASCIICharacterSetANSIdefinedastandardalphabetknownasASCII.ThishassincebeenadoptedbytheCCITTasastandard,knownasIA5(InternationalAlphabetNo.5).Thefollowingtablesdefinethisalphabetinbinary,asadecimal,asahexadecimalvalueandasacharacter.
127.This code is rather limited as it does not contain symbols such asGreekletters, lines, and so on. For this purpose the extended ASCII code has beendefined. This fits into character number 128 to 255. The following 4 tablesdefineatypicalextendedASCIIcharacterset.
Index
—Ω—
Ω,24,275
—1—
100Ω,93
100Mbps,402,412
10Mbps,402
155Mbps,402
16Mbps,402
—2—
24-bitcolour,462
256colours,394
2scomplement,159,222,223,227,277,424
—8—
80286,230,274,476
80386,5,231,232,233,236,243,274,276,476,485,649,653,655
80386DX,230,232
80486,231,232,236,239,241,243,245,252,254,276,415,476,653
8086,229,230,233,234,236,243,244,261,271,274,276,279,476,649,655
8088,230
8255,268
A
AA,245,254
accumulator,233,649,650,651,652,653
accuracy,91,309
active,232,233,268,270,286,295,300,506,507,510,532,597
ADC,21,649
addressbus,4,219,220,226,230–232,236,261,262
addressbussize,226,230
addressablememory,226
addressing
immediate,236
memory,226,236,237
register,236
addressingmemory,244
AIX,549
algorithm,3,129,135,219
alias,557,605,609,619
AM,413
American,391,413
ampersand,108,111,180,345,483
analogue,553
AND,35,36,41,64,96,97,247,423,424,598,611,649
angle,32,33,37,39,98–101,118,119,200,201,376,448
animation,454
ANSI,8,12,15,96,368,391,413,484,495,627
apple,29,229,319,476
ARC,492
archive,529,583,584,590
arctan,32,33,101
arctan(),32
argument,81,86,87,90,108,109,111,162,193,194,205,310,311,440,460,552,580–582,585,586,613,615,616,620
arithmeticoperator,421,422
ARP,391,413
arrayindexing,181
arrayofstrings,148,150,155,156
Arrayofstructures,181
arrays,121
arraysofstrings,610
arrowkeys,294,596
ASCII,24,60,61,67,143,159,160,240,286,363,368,391,413,424,483,493,565,573,586,628
BEL,191,475,549
CR,160,597,598,599
FF,245,252,254,392,393
LF,160
SUB,246,652
ASCIIcharacters,60,61,67,159,240,424,565
ASK,413
aspectratio,376
assemblerdirectives,252,654
assembly,224,239,240,243,265,266,267,655
AssemblyLanguage,5,219,239,243,245,247,259,271,415,649,654,655
asynchronous,413
AT,191,230
attributes,162,163,415,484,525,529,554–556,565,576,603,631
changing,556
au,464,482,485,490–493,499,501,530
audio,410,411,437,454,464,465
AUTOEXEC.BAT,530
averagesprogram,166
averaging,136
B
backspace,24
basepointer,234
BASIC,3,5,219,291–294,296,305,307,308,310,311,317,324,327–329,339,345,352,361,362,371,374,415,483,530,551
BCD,287
bell,549
BellLaboratories,191,475,549
bestpossibleunits,56
binary,3,4,5,63,79,108,159,163,168,169,170,171,210,211,215,216,220,221,222,223,224,225,243,244,265,271,272,273,411,413,415,564,570,573,631,632
address,108
commands,5,415
file,159,163,168,170,171,211,216,573,631
I/O,215
numbers,221
read/write,168
BIOS,263,279,281–284,285,286,287,288
printerinterrupt,286,287
bitshift,233,248,424
bitmapped,159,545
bitwise,35,41,210,247,424–426,447
bitwiseoperator,35,424
black,81,82,83,281,302,387,393,399,437,462
blanklines,173
blue,281,288,302,373,374,387,392,393,398,462,463,507,509,532,534,544
BMP,293,299,371,372,545
bold,385,472
Boolean,307,308,309,310,311,417,418,420,424,434,455
bitwise,247,424
logic,63,102
bootdrive,280,281
BorlandC,238,265–267,291,494,495
BorlandC++,6,291,494,495
Bourneshell,605,606
braces,9,41,68,132,150,179,426,427,428,444,450,483
brackets,122,124
bridge,413
browser,385–389,393,394,401,404,410,411,415–417,431,433,437,438,440,442,444,445
buffer,48,69,144,285
Busicon,229,475
Buttonsettings,313
byte,220
byteenablelines,232
C
C
arrays,121
fileI/O,162
functions,82,123
parameterpassing,107
program,9–12,16,18,19,23,24,26,35,48,91,93,107,111,113,114,145,146,148,159,166,168,172,178–180,223,405,418,552,561,565,570,572–574,592
Cshell,601,605,606,609,610,615–620
C/C++,415,437,439,446,449,450
C++,191–202,205,206,208,211–216,241,266,267,268,291,414–416,421,426,436,437,439,446,449,450,494,495
classtemplate,207
classes,192,195,209
constructors,205,209
datahiding,192
destructors,205
functiontemplates,206
I/Ostreamsupport,192
objects,192,417,429
overloading,192,193
templateclasses,192
virtualfunctions,192
callbyreference,109,111
capacitance,55,73
capacitivereactance,30,31
capacitor,30,63,73,149,150,183
caption,345
captionproperty,324,326,331,334,335,337,338
carriagereturn,160,586,628,632
carryflag,247,248,649,652
caseoptions,54
CBS,475
CD,265,479,491–493,495,515,535
centigrade,27,92–94,331,332
CGI,405
CGIscript,405
changingdirectory,552
characteralphabet,391,413
characterarrays,141,143,144
characterhandling,12,16
characterstrings,175
charactersandnumbers,243
click,362,363,364,372,373,375,377,378
clients,525
clockcycles,273–275
clockperiod,273,275
cls,375,379
cluster,529
CMC,649
COBOL,3,5,415
code
machine,4,5,239,240,415
object,5,6,86
source,5–8,10,13,23,87
colour,49–52,57,58,281,282,288,293,300–302,318,319,373–378,387,392–394,399,461,462,471,513,531,589
colourcode,49,50,51,52,318,319
COM1:,265
combinationallogic,94
combinations,220,296,365
comments,9,13,193,243,426,428
Commodore,229,476
commondialog,352,355,357
compilation,5–7,25,123,447,570
compile,6,7,494,565
compiler,5–8,11,13,16,18,19,23,25,32,86,87,108–110,122,123,181,193,238,310,415–417,438,439,443–445,464,469,494,570,571,572
complexarithmetic,184
complexfunctions,200
compleximpedance,186
complexnumber,37,101,118,184,188,192,199,200,203
complexnumbers,192,199
compress,411,553,554,558,559,560,575
compressed,159
compression,394
computing,229
conditionaljump,249,250
CONFIG.SYS,530
constants,9,13,49,54,113,243,355,357,365,366,447
controlbus,4
controlRegister,268,269
controls,293,302
conversioncharacters,91
conversioncontrolcharacter,24,26
copperwire,10,14
copying,renamingandremoving,558
countingthenumberofcharacters,147
CPU,239,241,245,252,254,567
creatingamenusystem,346
csh
eventnumbers,607
reexecutingevents,607
cube,449
currency,308,309,310
D
DAT,163,166,167,168,488
data
bus,4
definition,253
Register,265,266,267
segment,235,240,253,655
type,9–11,14,25,26,49,81,86–91,108,109,121,122,124,141,145,148,150,160,162,175,176,178,179,191,193,199,205–207,209,237,281,308–312,417,418,444,446,447,451,455
types,10,14,307,308,418
databaseprogram,176,178,186
date,201,280,307,309,310,311,434,477,478,484,485,487,490,554,561,563,568,569,585,586,591,592,619,627
DD,391,477,480,481,655
debugger,6,7,240,255–259,439,445,570,571
DEC,246,549,650
decimal,60,77,79,221–225,227,243,244,309,392,393,420,561,650
decimalpoint,25
decisionsandloops,317
declaration,11,14
declarationofvariables,11,14
degrees,32,33,39,65,100,101,156,462
del,286,346,478,519,544,545
Delphi,291
destinationaddress,234,244
dialogBox,345,354
Digital,265,268,271
Directorystructure,550
diskdrives,4,219,299,416,476,479,500,505,562,577
dividebyzero,44,55,56,70,73,167,168
division,308,421,422,649
do..whileloop,68–70,320
DOC,483,488–492,499,501,519,521,522,530
domains,526,527
DOS,236,243,254,279,280,281,283,285,286,291,476–479,481–485,487,490–499,501,505,506,513,519,525,528–531,535,536,539,541
cls,478
copy,496,500
date,477,563
delete,495,628
dir,484,485,490–493,494–500,563
erase,495,496
exit,280,281,283,285,286
filenames,483
format,479–481
mkdir,493
run,535
services,279
startingandstopping,478
time,477,479,487,563,567,568
type,493,496,500
unformat,480
ver,477
version,280,477,487
DOS-based,243,519
draganddrop,367
E
earth,29
Edinburgh,324
edit,5,294,440,441,445,494,497,593,594,597
editor,5–7,159,166
eece.napier.ac.uk,398,460
EEPROM,4
electronicmail,525
EMspectrum,45
EMwave,45,46,47,55
encapsulation,191
EOF,164
equates,254
equivalentresistance,12,15,20,34,39,40,57,58,79,115,116
error,10,16,19,23,25,44,55,56,72,86,87,142,145,164,165,168,209,213,284,287,310,311,321,373,399,401,617,631,632,633,634,635
errorprocessing,213
escapesequence,24
Ethernet,390,391,402,408,409,411–413,434,435
eventhandling,430
executable,5,7,8,12,16,159,405,411,417,555,556,561,570,573,574
exp(),88,90
Explorer,417,531
exponent,25,160,424
F
Fahrenheit,27,92,331,332
farads,31,55
FAT,528,529
faulttolerance,412
FAX,467,468
FC,490,491
fclose(),163
FDDI,390,402,408,411–413,434,435
DAS,650
feof(),164
FET,78
fflush(),48
fflush(stdin),48,69
fgetc(),164
fgets(),165
file
attributes,163,529,554
binaryread/write,168
binary,159,163,168
I/O,159
pointer,160,162–164
pointers,214
systemstructure,481
system,491,499,505,513,525–529,539,578
systems,505,525,526,528
text,159,160,163,165,166,174
transferprotocol,587
find_nearest_pref(),132
firmware,3,192
floatingpoint,11,14,15,24,25,32,152,160,166–168,174,175,176,178,215,222,308,311
floppydisk,478,479,480,481,500,501,505,515–517,521,529,535,546
fopen(),162,163
forloop,59,63,77,96,155,320,427
forceofattraction,29
formatdescriptor,35
forms,293,323,324,405
formsandcode,324
FORTRAN,3,5,159,219,415,492,551,562,570,571,584,614
fourth,65,129,602,606
fprintf(),165
fputc(),164,165
fputs(),165
frame,298
France,324,330
fread(),168
freediskspace,279,280
frequencies,30
frequency,30,31,32,33,45–47,55,73,98–100,101,153,154
fscanf(),162,164,165
ftp,443,565,587
function
declarations,86
header,81,105,109,111
prototype,84,85,87,88,96,111,115
general,12,15,81,106,428,444,448,488,627
fwrite(),168
G
gateway,405
gateways,261
get_float(),155,181
get_int(),181
get_values(),111,114,166
getchar(),25,26,48,53,69,75,76,147,164
gets(),25,147,165
GIF,159,393,394,416,459,471
globalvariable,82,83,84
gradient,28,29
graphicaluserinterface,593
ground,598
H
hackers,416,528
handshaking,269,270
hardware,3–5,219,229,233,263,279,412,415,437,476,505,513,528
HD,480,481
header,8,9,13,23,25,26,32,44,51,81,86,87,105,106,109,111,192,209,265,266,267,385,386,403,439,469,563
headerfile,8,9,23,25,32,51,86,87,201,439,563
help,533
helpfiles,159
helpmanuals,357,481
hertz,31
hexadecimal,24,25,35,77,79,108,224,225,236,237,243,302,373,374,378,392,393,420,629
hierarchicaldecomposition,82
high-levellanguage,5,219,243,415–417,436
history,605,606
hobbycomputers,3
hosts,562
HPFS,528
HP-UX,549,550
HTML,385–388,390,391–397,399,401–409,413,416–419,429,430,432–436,438,440,441,450,451,455–460,463–468,470
anchors,401
backgroundimages,393
colours,392
definitionlists,391
displayingimages,394
hexadecimalcolours,392
horizontallines,397
inputtypes,407
links,387
lists,388,491
menus,345,409
orderedlists,388
script,386–388,390,391,394–397,399,401–404,406–409,416,440,441,450,451,455–460,463–468,470
tables,403
unorderedlists,388,390
http,387,394,398,416,431,438,443
hubs,412
Hughes,475
Hz,153,154
I
I/O
classes,209
digitalprograms,271
digital,265,268,271
inputtingabyte,265
isolated,261,263
library,208
memorymapped,261,262
outputtingaword,267
stream,192,208,213
streams,208
IBM,229,230,412,475,476,549
ICprogrammers,21
icons,371,372,373,513,514,515,532,538
IDE,265,494,500
IEEE,309,448
if(),41–43,45,49,426,427
if…elsestatements,41,427
images,293,299,393–396,459
impedance,32,73,98,100,101,151,173
impliedaddressing,236
information,4,5,8,9,152,159,209,220,229,243,279,299,312,314,387,391,394,402,403,405,413,415,429,437,476,479,480,483–485,493,505,510,519,526,537,541,545,550,552–554,562,567,570,571,573,586,588,591,620
initializinganarray,132
input/output,4,9,12,16,21,22,23,81,161,162,209,219,233,261,268,416,439,562,583
insertmode,594,595,597,598
integrateddevelopment,6,7,494
Intel,229,230,231,233,415,475,476
Intelmicroprocessors,230,231,233
interface,81,231,232,261,265,291–324,437,446,453,505,549
interfacingwithmemory,262
Internet,411,417,437,438
InternetExplorer,417,437
interrupt
1682h,281
1684h,283
1686h,284
1688h,284
1690h,285,1Ah,287
1693h,279
interrupts,279
IP,234,391,412,413,437,526,549
IPaddress,391,413,437
IPX,412
ISDN,435
J
Java,159,191,403,404,414–418,421,422,428,434,436–472
applet,415,416,418,437–458,460,463–472
compiler,416,417,438,439,443,444,464
script,442
JPE,651
JPEG,159,393,394,459,471
JPG,416
K
kΩ,56
keyboard,4,5,9,12,16,21,22,25,26,48,69,144,192,202,216,219,264,279,281,285,288,431,455,457,476,505,519,559,560,575,582,596,618,632,633
keyboardbuffer,144
keypress,361–363,368,458,459
keystroke,285,286,471,490,546,559,587,591,594,595,606
keywords,5,10,12,15,41,176,179,415,426
Korneshell,605
L
LAN,402,411
length,52–54,141,143,144,148,220,310,371,407,428,471,620,632
libraries,5,9,12,15,23,81,86
library,12,16,25,144,208,352,444,447,469,545,563,573,583,584
LIFO,250
light,13,45,271,273,278,281,393
limitingrangesofinputs,69
linebreak,386,404,412
linker,5,6,7,86
Linux,549
listingcontentsofafile,557
listingdirectories,553
ln(),90
Localandglobalvariables,83
localareanetwork,412
localvariables,81,82,106,610
log(),88,90
logarithms,90
logical,41,308,421,423,426,611
logicaloperator,96,423,424
loginintothesystem,550
longinteger,160,237,308,309,630
longword,220
lostfocus,368
lowercase,12,48,53,58,145,590,628,629,630
LZH,492
M
MΩ,56
MAC,390
MACaddresses,390
machinecode,4,5,239,240,245,246,261,415,416
machinecodeandassemblylanguage,240
macros,5,8,9,53,253,415
main(),82–84,85,168,193
makingandremovingdirectories,557
manganese,52
MASM,253,491,492,493
mathematicalfunctions,12,16,201
memory,3,4,7,11,14,26,107–109,122,144,181,205,215,219,220,221,226,230,232–241,244,246,248,251,259,261–265,268,278,286,291,393,454,526,549,633,651,653–656
address,3,4,26,108,122,144
addressing,226,236,237
cache,230
map,108,109,261–265
segmentation,236
menu,6,7,57,155,186,294–296,300,301,302,345–349,351,353,358,409,430,467,468,494,507–510,512,516,522,534,539,543
menueditor,345,346,347,350
metafile,293,299,371
mF,55
microprocessor,4,5,219,220,229,230,231,262,415,476
Microsoft,159,191,253,262,263,266,267,268,291,310,330,352,417,476,481,505,506,510,514,517,519,525,530,543
Assembler,253
Office,476
VisualC++,191,291
Windows,262,263,291,310,352,476,481,505,510,517,519,525
microwaves,45
MIME,411
model
large,238
small,238
modularprogram,81
module,105,106,118,252,295,296,347,570,571,655,656
modules,292
MOS,229,476
MOSTechnologies,229,476
Motionvideo,159
Motorola,229,415
mouse
control,533
controls,508,533
down,364
up,364
MOV,244,651
moveinstruction,244
movingarounddatainmemory,251
MPEG,410
MS-DOS,513,525,528,529,536,541
multimedia,408,410
multiplechoiceexample,324
multiplication,422
multitasking,416,525,526,549,567
N
NAND,35,36,96
Napier
EECEdepartment,398,460
negative,85,90,145,222,234,235,246,249,311,320,426,462,607,629
negativenumbers,222
nestedloop,96
Netscape,417
network,18,402,408,409,411–413,435,437,479,497,515,525–528,530,531,537,587
networkmanagement,412
networktraffic,412
networking,525,531
NewYorkTimes,475
newline,23,24,165
nF,55
nibble,220
NOR,35,36,64,96,97
NTFS,528
null,143,144,147
numbersandrepresentations,222
O
objectcode,159
objectproperties,323
object-oriented,291
objects,191,192,207,293,297,299,303,340,341,350,362,371,417,429,432,434,435,463,465
octal,24,25,77,224,225,243,420,576,586
OLE,299,330
openingafile,162
operatingsystem,10,21,159,291,401,415,476,505,525,526,528,530,546,549,567,605
operators,307,425
opticaldisks,479
OR,35,36,41,96,97,210,247,278,423,424,457,611,651
ordered,388,389
organization,391,413,527
OS/2,528
OSF/1,549
OSI,390,413
P
paragraph,386,550,598
parallel,11,12,15,19,33,34,39,47–49,57,58,70,79,114–116,151–155,186,194–199,265,283
parallelresistors,19,33,39,57
parallel_impedance(),152
parameterconversion,24
parameterlist,86,106,121,123,125
parameterpassing,81,84,105,106,107,198,437
parameters,24,25,29,52,81,82,84,86,87,89,100,104–106,109,142,152–155,198,201,284,312,316,363,397,404,428,440,444,457,461,463
Pascal,3,5,7,13–16,18,19,21,22,23,26,27,31,32,35,36,41,48,49,53,54,68,88,91,92,93,97,100,104,105,106,113,114,118,119,121,124,132,141,142,150,152,154,159,161,166,168,172,175,176,177,219,225,237,261,266,267,293,307,308,318,320,401,415,436,437,483,494,500,571
arrayroutines,142
arrays,124
compilation,7
fileI/O,161
functions,88
parameterpassing,106
program,13,15,16,18,19,23,36,54,91–93,97,100,113,114,150,161,166,168,172,176,177
string,141,142
stringconversionroutines,142
passingarraystoCfunctions,123
passingarraystofunctions,124
passingbyreference,81
passingbyvalue,81
PC,5,6,7,159,229,230,233,236,240,262,263,272,283,291,415,437,438,440,476,478,479,487,493,505,506,510,520,525,549
PCX,483,490
peer-to-peer,525,526
Pentium,231,233,236,243,276,415,476
permutations,63,96,578
pF,55
pixels,371,377,378,396,397,403,404,433,440
pointervariable,122,124
pointers,81,107–109,110–115,122–124,144,145,147,160,162–164,180,198,214,237,238,437,505
far,237,238
near,238
nearandfar,237,238
withfunctions,109
polygons,463
ports
number,284
PortA,268–270,273,276–278
PortB,268–273,276–278
PortC,268,269,270,278
Postscript,159
power(),87,90
precedence,307,308,425,447
precisionspecifier,25
preemptive,526,549
preemptivemultitasking,526,549
preferredresistorvalue,135,136
presentation,309,401
printservers,525
print_results(),112
printable,628
printerport,287
printf(),23,24,25,53,86,87,91,145,162,165,192,208,629
priority,425,568,570
privatekey,195
procedures,293
processorflags,235
projectfiles,292
prototyped,32,44,86,87,144,199,200,265–267,268
prototypes,86,93,94
publicmember,195
pushandpop,250
putchar(),23,164,165
puts(),9,13,23,24,165
Q
quadraticequation,42–45,56,105,111,113,114,334,335
quadraticequations,111
quadraticroots,334
R
RADAR,492
radians,32,33,38,39,100,101,376,634
radio,45,293,408,431,467
RAM,4,220,263,493
range,3,11,14,70,71,104,132,139,199,223,231,263,301,308,309,310,311,321,336,337,345,374,392,446,448,634,635,636
Raytheon,475
RCcircuit,61–63,151
RCA,475
read_data(),168
readingandwritingonecharacteratatime,171
readln(),154
recast,88
recordsinPascal,175
rectangular,186,448
red,288,302,373,374,392,393,398,462
register,233,235,239–241,244,246,248,251,253,259,265–274,279,281,285,649–655
relationshipoperator,422
repeat..until,59,68,69,70,77,142,161
repeatingprogram,69
resistance,10–15,19,20,23,32–34,39,40,48,49,52–58,69–73,75,76,79,98,100,104,109,114–116,133–136,153,154,196,197,198,208,216,321,338,339
resistancecalculation,336
resistanceofaconductor,52
resistivities,53
resistorcolourcode,49
resize,362,368,369,511,538
return,84
flag,111
statement,84
value,10,84,85,87–89,110,164,165,213,279,315,429,444,630–636
RGB,302,373,374,375,376,377,392
ringnetwork,412
RLseries,32,66,98,99,154,155
RLseriescircuit,32,66,98,99,155
ROM,4,263,265,479,515,535
root,32,43,44,45,55,56,70,105,111–114,200,334,448,449,452,481,482,517,550,560,561,574,576,577,606,635
roottype,111,113,114
RR,302
RS–232,284,435
runningaverageprogram,126
S
sampling,136
scanf(),25,26,35,48,86,87,91,111,145,154,162,165,208,629,632
schematic,31–33,63,95,97,98,151
SCO,549
scrollbar,507
search,8,147,172,305,508,509,581,599,601,613
sectionheader,385
sectors,280,479,529
segment,235–237,239–241,244,245,251–255,280,281,283,286,526,651,653,655
serial,480,481,484–498,541
serialcommunications,284
serialport,283,284,285
seriesRL,98–100
servername,398
servers,525,537,538
shellscripts,615
shellvariables,612
shiftinstructions,247
shift/rotate,247
shortinteger,109
signedinteger,11,14,24,176,178,223,224,227,424
silver,52
Sinclair,229,476
SMTP,443
software,3,4,9,10,13,18,141,191,229,230,236,239,262,412,414,437,476,494,506,510,525,549,550,650
softwareengineers,3
Solaris,549
sort(),129
sortingprogram,129
sound,159,459,464,472
soundfile,159,514
source,5,6,7,8,10,13,23,31,78,82,87,142,234,246,252,367,386,442,518,558,561,565,571,653
sourceaddress,234
specialcharacters,556
specification,3,25,401
speech,413
speedoflight,13,46
SPX,412
SPX/IPX,412
sqrt(),86,87,100
squareroot,32,43
squares,65,299
sscanf(),145
stackpointer,234
standardfunctions,12,16,633
standardinput,559,575,583,632,633
standardinputandoutput,559
standardoutput,559,574,580,586,601,633
standardstringfunctions,144
standards,391,413
statementblock,41,42,59,60,68,318,319,321,427,428,449,450,451
statements,422
repetitive,59,81,105,121,159
static,12,418,445,446,449
statements
logical,41,426
statusregisters,234
stdin,48
stopbit,284,413
straightline,28,29,104,107,111,201
strcat(),144
strcmp(),146
strcpy(),144
stringmanipulation,141
stringvariables,610
strings,141,144,147,420,445
strlen(),144
strlwr(),144
structurechart,85,86,89,98,112,114,115,132,151,181
structures,181,186
arrays,181
dotnotation,176,178
members,175,176,178
pointeroperator,180
structuresandRecords,175
SUB,246,652
subroutinecalls,250
SunMicrosystems,191,415,438
swap,106,107,110,546
swapped,129
switchstatement,49,54,617
switch(),49,54
synchronized,4,220,413,446
synchronous,265
syntax,86,265,266,267,415,417,418,421,425,427,428,450,505
systemdate,280,563
systemtime,279,280,283,287
SYSTEM.INI,541,545
T
TAB,297,488,543,546
tables,403,562,593
tangent(),91
TCP,391,412,413,437,526,549
TCP/IP,391,412,413,437,526,549
TD,403,404,405
television,471
telnet,443
temperatureconversion,332
temperatureconversionprogram,331
terminal,586,618
terminateandstay,280
test,6,7,26,28,29,31,35–37,39,40,45,55,57,58,60,79,86,89,90,92,97,163,167,168,170,185,201,205,206,213,234,271,285,286,321,332,351,428,436,440,449,451,458,459,464,478,569,573,574,602,611
TexasInstruments,475
text,159,212,282,323,326,327,330–336,351–355,364,365,366,368,372,373,468,483,514,545,593
blink,385
editor,166,385,401,494,575,593
file,159,494,514,545
I/O,212
keyword,161
textbackgroundfunction,57
timestepdelay,136
timing,261,273
token,9,254,255,408,412,413
TokenRing,390,402,408,409,412,413,434,435
MAUs,412
tokenrings,412
tolower(),48,53,54
topology,387
TR,403,404,405
tracks,479
traffic,278,412
transientresponse,61
transistor,475
transistors,475
truthtable,63–65,94–97
TurboDebugger,239,241
TurboPascal,5,7,14,15,18,48,237,266,267,494
TXT,483,490,496,497,498,545,546
typekeyword,124,176
typesofroots,45,334
U
UK,398
uncompress,575
uncompressed,575
unconditionaljump,249
UNIX,8,405,438,492,525,528,549,550,552,554,559,562,566,567,570,572,576,584,589,591,593,605,606
banner,584,585
cal,563,565,584,585
cat,557–566,574–580,583,591,600,606–609,615,619
cc,557,561,562,569–572
chmod,556–577,615,616
chpass,585
compilingCprograms,561
cp,557,558,564,566,572,573,612
date,585
dbx,570,571
df,577
diff,578
du,573
echo,586
f77,562,570,571
file,573
find,580
finger,586
grep,581,582,593,600,601,603
head,581,582
kill,567,568,590,609,618
lint,572
In,580
lpr,568,587,608
Is,552–560,564,566,567,570,571,573–577,579,580,589,603,606–609,619
mail,587
more,553–556,565,579,598,605,608,619,655
mv,557,558,566,578,579,619
nice,570
passwd,562,581,588,605,606
pipes,560
processcontrol,567
ps,567,568
redirection,559
rlogin,588,589
rm,558,564,569,571,579,580
sed,557,593,599,600,620
sleep,589
sort,601,603
spell,565,589,593
stty,557,589,590,592,618
tail,582
tar,553,590
wc,582,583,593
who,562,590
write,591
unload,362,369,431
unorderedlists,388,389
upcase,48,49
URL,387,398,405,430,443,460
URLs,437
USA,477
V
varkeyword,106,125,420
variables,81–85,89,96,106–109,111,113,114,121,152,193,197,199,201,253,275,307,309,312,418,419,420,421,429,446,552,571,605,609,610,612–614,655
initialization,12
substitution,609
velocity,71,72
version,229,230,280,310,385,438,439,440,443,464,475,476,477,487,505,506,510,530,537,541
VGA,263,530
video,159,281,282,288,393,411,437
visible,45
VisualBasic,291–294,296,305,307,308,310,311,317,324,327–329,339,345,352,361,362,371,374
controlsandevents,302
files,292
formwindow,296,297
language,305
menubar,294,507
objectbox,300
projectwindow,295,296,302,306
propertieswindow,295,297,300,301,531
toolbox,296,298
visualeditor,567,593,597,607–609,614–616
example,597
insertmode,594,595,597,598
substituting,595
volatile,12,446
voltage,23,31,39,40,61–63,72,73,75,76,104,216,321,337,338,339,341,422
W
WAV,464
wavelength,45,46,55
web,415,416,437
WesternElectric,475
UNIX,562
while(),68,145,146,428,450
white,212,302,387,393,399,462
WIMPs,505
WIN.INI,541–543,545
Windowobjects,432
Windows
capturingascreen,543
closingawindow,510,534
deletingfiles,518
desktop,506
fileextensions,545
Filemanager,513,514,515
formattingadisk,515
help,509,533
maingroup,513,521
movingandresizingawindow,509,533
movingfiles,517
quitting,508,509,533
running,506,519,530
selectingadirectory,515
selectingadrive,515
startup,542
swapping,543,544
terminatingprograms,544
Windows3.x,506,525,529,541
Windows95/NT,159,262,263,291,476,477,505,525,526,528,529,530,531,537,541
DOSwindow,513,536,539
Explorer,531
MyComputer,531,535,537,538
networkneighborhood,531,537
startbutton,531,534
WindowsNT,159,291,438,440,476,477,487,505,525,526,527,528,530,531,537,541
networkdrives,537
WK3,484
WMF,293,299,371
word,220
wordprocessor,159,514
words,60,147,173,246,446,582,584,589,593,594,620
workgroups,526,527
worksheet,18,37,39,56,57,67,79,104,118,139,156,174,188,487,499
workstation,437,526,528,549
workstations,525,549
WP,488
Writingtofiles,165
WWW,191,385,386,387,389–398,401,411,413,415,417,437,438
X
X
xterm,557
X/Open,549
XOR,247,424,653
Z
Zilog,229,476