Home

Table of Contents

image

Contents

1. C allows other streams to be set up These streams must be declared justas identifiers are declared Thus steams that are 10 be used fo input are declared an having the Sp st rean amd those that are used for output are declared as having the type 8251ean Once sirean has Boen declared it must b eonmected 1o an externa file M aes ane ging to be used th fle zat roant must be included in th program 11 2Connecting Streams to External Files The sre mast first be declared The names for steams follow the same rules of formation as identitiers Thu the following declaration declares the steams for input and the stream out for up To connect these streams to the appropriate external fles the oper function is wed The spun fupeton ixa member function of the stream class andl 1o comeet he seat 1 103 fle inane saat the following statement is used The general foem for a stream with identifier srearmame and a file with name filename streamname open filename M the file inant cat did not exist or could not be found then this open function will fal Failure of the opon function is ested by using the function streammname 251 0 Which returna zeoe ifthe oper function failed When using the open function Cale Should always be tested for asin the flowing example Neic In this example itis assumed that the failure occurs within the nats program This means tht he return statement exiis the nain program and hence
2. To get sound this difficulty al high evel programming languages use the concept of a ita saracu calle an Array 102 Arraysin Cst Tis Neic An area is a data structure which allows a collective name to be given to a group of elements which al has the same type An individual element of an array is identified by its own unique index or subscript An ary can b thought of as a collection of numbered boxes each comaining one daia item The mambet associated with the box Is the index of the ern To aocess a particular iem the index ofthe box associated withthe ies fe used o access the appropriate box The index mst be an integer and indicates the position of the element in he aray Thus Khe elements of an aray are ordered by the inden 10 3 Declaration of Arrays An aay declaration i very similar to a variable declaration First a type s given for the lees of the aray then an identifier for the aay and within square Brackets the umber of elements in the array The numberof elemens must be an integer For example data on the average temperature over the year in Britain for each of the hist 100 years could be stored in an array declared as Tellows This declaration will cause the compiler to allocate space for 100 consecutive 103t yariables in memory The umber of elements in an array mast be fixed at compile Ume Tes best to make the amay size a constant and then if required changing the vale of the constant ca
3. he value of one argument in the function IF you mast past an argument by reference you tt program i on your ow You therefore use poinent 5 4 5 Pointers and Arrays One of the most common problems in programming in C and sometimes C is the understanding of pointers and arrays In C Co bth are highly elated with some smal but essential differences You declare pointer by ping an asterik between the dita type and the name of the varisble or function You access the content of a pointer by de referencing it using again the asterisk As in other Languages you must provide some space far the value to which the poiner points A pointer to characters can be uscd to point to a sequence of characters the siring Strings in C are terminated by a special character NUL 0 ar as enar O Thus you can hve strings of any length Strings are enclosed in double quotes Neic In this case the compiler automatically adds the terminating NUL character Now sirp points to a sequence of 6 characters The fist character is Iis the second e and so forth We cam acon these characters by an index in st The first character also equals st which can be written as Mary 0 This eds to something called pointer arithmetic and which one of the powerful features of C Tima we have the following equations Note that these equations are tue for any data type The addition is mot oriented to bytes itis oriented othe size of he cor
4. Properties of a clase B We say A thet from B Objects of class A thur have acess to ates and methods of elass B without the need to redefine them The flowing Ta Neic Aefiion defines wo ems with which we ae able to refer to participating classes when They use iahetance Definition Super clas Subelas If class A inherits from class B then B is called super elass of A A is called subelars of B Objects of a subclass can be used where objece of The cormesponding super class are expected This is due wo the fact that objet of the subclass share the same behavior as objects of the saper las An the Ieraure you may also find other terms for super class and subclass Super lasses are also called parent classes Subelsss may also be called child classes or jast rived classer OF course you can again inbert from a subclass making this elass the Super class of the new subclass Ths leads to a hierarchy of supet clwatbeliss Felson If you daw tus hierarchy you pet an inentance graph A common drawing scheme ito use rowed Iines 1o indicate the inberitance relationship Between two classes or objecta In our examples we have used inher om Consequently the arrowed line sarts Trom the subelass towards the super clas usa in Figure 61 Pse herefrom owe Pure Asi eens pp nthe erature you also find asrations where the arrowed lines are used just the other Way around The direction in which the arrowed line is used
5. evaluated and its value returned asthe operators eat Thus ji assigned 6 The comma operator nodes a particular pitfall when using n dimensional arrays with P gt 1 A frequent error is to use a comma separated list of indices to uy to access an element imt mats IONNS 1 2 dim mae Tmavig 2 M WONT WORK inant MOK What actually happens inthe first case is that the comma separated isi interpreted as the comma operator Cansequely the resul 2 which leads to an assignment of the ders othe thi five elements of the maa Some of you might wonder What C does With values which are not used Far example in the assignment steals We have seen Before a we kave thee lines which each regara 12 The answer is that C ignores values which are ot used This eads to some strange things For example you could write something like But les forget about these strange things Lats come back to something more useful Lars alk about funtion Neic 5 1 4 Functions As C is a procedural language i allows the definition of functions Procedures are simulated by funetions returning ao value This value a special type called vs Functions are declared similar to variables but they enclose their arguments in parenibesis even if there are no argumens the parenthesis mast be specified To actually define a function just addins body C only slows you to pass function argumens by value Consequently you cannot change
6. ind espr is the step ast ait Jongs to postion indiated by GET The destination i Tabet followed by clon apy wt faiae a ENTS ee Ca retera Fp Tatura rors Fonction W con fmm void retarnsooBl be sed with out additional argument Otherwise the akee of espr i retuned RETT NEE maata al tap ATV ToT ave comerpr simts poral with the case causes Enecston ase conser simts ontines at the ane that matcis BE WARE You must use break to leare stavne sms the suiten if yom don t want execton j of follwing ease closes M no ease Chanso matches and a dof cose ex fat the statements of the deal clause are exec wale Cap at Repent sit az ong capes PRUE 5 1 3 Expressions and Operators In C almost everything is an expression For example the assignment statement ret the Value ofits right hand operand As a side effect it also sets the Value of the left hand operand Thus Neic Sets the value of r to 12 assuming that dr has an appropriate type Now that the assignment is also an expression we can combine several of them for example What happens The fist assignment assigns Kr the valie of its righthand side This is the ale ofthe assignment toe But his ete value of the assignment 10 iz The vale of This laer is 12 which is returned toje wbich e returne to ke Thus we have expressed Truth in C is defined as follows The value O zero stands for FALSE Any other value i
7. 8 5 1Example wh 2e loop Printing integers The following un 1e statement prints out the numbers 1 10 10 cach om a new line 8 5 2Example waste loop Su Arithmetic Progression The following portion of C uses a uht 1e statement to produce the sam 202039 t whee value for entered by the user I assumes that integer variables 1 and sun Mave been declared To Nec There are several important points to note ew 1 The condition amp lt n requises hat and n must have values before the wns 20 Joop is executed Hence the Initialization of t andthe entry of a valus Tor r Befane the uh 1 statement H is possible that ante loop may not be executed at all For example if the user teed vale foro then the condition lt n would be false initially and the Sttemeat part of the 1 loop would never be entered 3 When accumulating the sum of sequence the variable in which we accumulate he sum must be Initiaized to zero before commencing the summation Note also that ithe user erered a value Tor that was Tess than 1 then the initialization of ov would mean that the program would reurs zero athe accumulated tt is zero this certainly a sensible value 4 Thee is no unique way to wile 4 ni 2e statement for a particular loop For example the lop in dus example could have been written as follow Without changing the result 8 5 3 Example white loop Table of sine function The following program prod
8. In particular he specification cannot be given 10 the computer using natural language Moreover it Cannot yel just be 2 description of the problem or task but has 1o contsin information abour how the problem iso be solved or the task is tbe executed Hence we need programming language There are many different programming languages and many ways to classify them For example high level programming languages are languages whose syntax i elatively lose 10 natural language whereas the syntax of low level languages includes many Tschnical references to the ats and bolts 0 s and 1 et of the computer Declarative inguaze as opposed 1o imperative or procedural anguages enable the programmer 1o minimize hit or her account of how the computer i solve a problem ar produce 2 parieular output Object oriented languages reflect a particular way of thinking about problems and tasks in terms of identit ying and deseribing the behavior of the relevant objects Smatlalk is an example of a pure object oriented language C includes facilites for ebject ocened programming as well at for more conventional procedural programming Proponents of different languages and styles of languages sometimes make extravagant claims For example t is somtimes claimed that well winen object oriented programa elect the way in which humans think about solving problems Judge for yourselves 1 24 Programming Languages All computers have
9. This type of method definition is useful for small and simple bodies It also improves performance because bodies of inlined methods ace cpt imo th code wherever a Ealo such a method takes place On the comer calls to the set methods woul result in ea function call We define These methods outside of the class declaration This makes it necessary Wo indicate which class a method definition belongs 1 For example another cans might just define a method ser which s quite different frons that of Point We mast be able to define the ope of the definition we therefore we the scope pero Here we define method se st within the scope of class Paint The object point an use these metas 1o set and pe information aout sl a Nec The question arises about how the methods know from which object they are invoked This s done by implicitly pasting a pointer to the invoking object to the method We ean access his poiner within the meds as tnx The definitions of methods seik and Set make use of elass members and y respectively I invoked by an object these Members are automatically mapped to the earect object We could use tis to ilustrare what actually happens Here we explicitly use the pointer tnus to explicity de reference the invoking object Fortunately the compiler automatically inser these de references for class members hence we rally can use the fist definitions of set and se However t
10. example which demonstrates tis The question is wheter the old or new vale of i used as the subscript into the armay a depend on the order the compiler uses to evaluste the assignment The conditional operator isan abbreviation for a commonly used 12 statement For example to assign max the maximum of a and b we can we the following 1 slemen These types af s statements can be shorter written 3s The nex unusual operator is the operator assignment We are often using assignments of the following form forerample a Neic In these assignments the left hand value also appears on the right side Using informal speech we could express this as set the value oft the caren value of mile hy the sum of the value of j and 1 Using 4 more natural way we would tater say Mall with the sum of the value of j and Callow us to abbreviate these types of assignment to We can do that with almost all binary operators Note that he above operator assignment reall implements the long form although Is no in parenthesis The last unasu operator the comma operator Itis best explained by an example This operator wakes its arguments and evaluates them from left to ight and returns the ale ofthe ightoat expesion Thus in he above example the operator first evaluates e wbich as a side effect increments the vale of i Then ihe next expression HAS it evaluated which adds 2 1o leading To value of 3 The third expression 1t
11. its a Base object Consequently oo 25 defined in lass Base called The all to Bar is not subject W this content resolution I is not masked as virtual Consequently burt ss called in the scope of elast Base The second fall demo aks a Derived object a its argument Ths the argument os filed with 4 Derived objec However o itself just represents the Base part of the provided object a derived Now the cll foot is evalusted by examining the content of o hence i it falled within the scope of Derived On the other a b is still evaluated within the Scope of Base Definition Polymorphism 3 Objects of super classes can be filled with objecte of their subclasses Operators and methods of subclasses can be defined in wo conte 2 Based on object type leading t0 an evaluation within the scope af the superclass 5 Based on object coment leading to an evaluation within the scope of the contained subclass The second type i called polymorphism s Chapter 5 Introduction to C Nee Introduction to C 5 This secon she Tirat part ofthe notion vo Ces Here we focus oa C ram which CCH was adopted C extends the C programming language with stone typing some features an most ingot object oriented concept 51 The C Programming Language Developed n the ate 1970s C gained a huge success due to the development of Uses Which wat almos ently wien in Ihis language In conrad to oiher high level languages pogr
12. oop again 2 2 These concepts are used in the for statement which is designed for the case where loop is to be executed starting fom an initial vale of soe control variable and looping until he control variable sates some condition neath updating the vale ofthe control variable each timme round the lop The general foem ofthe ror statement is toe nai z est s update Which executes the initialize statement when the zox saement is first entered the test expression is then evalusted and if true the loop statement is executed followed by the Update statement The eyele of Nlestexecuse statementsupdate is then cominued unti the TEs expression evaluates to false coal Ihen passes to the next alalement in the progam 7 1Esample for statemen Prin 10 integers The equivalent or statement to tbe nse statement Neic Which initially sett ss the compared with 10 ti ss dhan or equal to 10 then the saerent 1o output execute 1 then incremented by 1 and the condition 1 lt 25 is aguin tested Eventually 1 reach the vale 10 this Value i printed and it incremented to 11 Consequently on the next test of the condition the condition evalates to fase and hence exits is macke from the loop 8 7 2Example or statement Print table of sine function The following loop tabulanes the sin function fom x 9 0103 2 8 in steps ofo 1 Note bow an integer variable 1 is used to contol the loop while inside the Loop th
13. which follow we use a notation which i ot programming language specifie In this notation 232 1 s deotes the definition at a eis Enclosed in the ely brackets are Ivo seetions s ipares apd serhaa wbich define the implementation of the daa structure and options of the Corresponding ADT Arain we distinguish the avo levels with different tems AL the implementation level we speak of anributes wbich are elements of the data site At the ADT level The same applies to method which ane the implementation of the ADT operations An our example the data structure consists of only one element a signed sequence of igi The corresponding abune ian ordinary integer of a programming Language We only define two methods serValurt and adVae vepresenting the Wo operations srt ndadi Definition Class A elast ix the plementation of an abstract data sype ADT I defines atribute and methodi sich plement he data structure amd operations of the ADT respectively Instances of classes are called objec Consequently classes define Propenies and behavior of sets of objects 42 Object Neic We have talked of instances of abstract employers These instances are actual examples ofan abstract employee hence tbey cousin actual values 10 represent 2 particular employee We call tese instances objets Objects are uniquely identifiable by ame Therefore you could have tvo distinguishable objects with he same set of Sales This is sim
14. 3 as an approximation to the square roo of 10 gives the following sequence of approximations old new 3 Bewy2 317 Aur Garama 31623 2 1623 1073 162302 103 iom H can be seen that the sequence of approximations is rapidly converging to the correct valne wbich is 3 16227766 This may not always be te in every application of erative Inehods but in the cuse of square rots H will always happen longs the finst approximation chosen is positive In the algorithmic description above the phrase while o1a_app and nouape are not lowe enough was used How do we test this In the square root example i might be decided hat the new approximation woul be acceped the correct ve of the rot ho it differed by lest than 0 008 fom the previous approximation This Would mean That the estimate of the roat was correct othe dina places It might be tempting to tt the et Tas Nec but in the second iteration tis test would give 3 1623 3 17 gt 0 0005 which is equivalent 1o 0 2077 gt 90008 which is Talse causing the eration process would stop prematurely The problem i that i nen appsis_ape is evet negative then since 2 epave mmber cin never be greater than a positive number the condito will become fale however large the difference between reu_spp and ois seo The solution to this problem is to test the absolute magnitude wikout egard io sigh of nev sep and ra app Cet has a function s x which returns the abolute value of x L
15. An object invokes a method as 44 Summary To view a program as a collection of interacting objects is fundamental principle in object orientsd programming Objects in hs collection reac upon receipt of mesages Changing heiz state according to invocation of methods which might cause other Messages sent 1o other objects Nec In ths figure the program consists of only four objects These objects send mesiages to each other an indicated by the arrowed lines Note that the third object sende ll 3 message How does this view help us developing software To answer this question lets fecali bow we have developed software for procedural programming anguapes The first ep was to divide the problemn to smaller manageable pieces Typically these pieces ere oriented to the procedures wbich were taken place to solve the pole rather than The involved data Asan example consider your computer Especialy how a character appears on the sereen when you type a key in a procedural environment you write dowa The several stepa necessary 1o bring a character on the screen 1 Wai ut a key i pressed 2 Get key value 5 Write key valu at current cursor position 4 Advance cursor postion You do not distinguish entities with well defined properties and well known behavior In an object oriented environment you would distinguish the interacting objects ey and Screen Once a key receive a message that it should change in state 10 be pressed iS Co
16. Roughly speaking modules consist of two fle types interface descriptions ad implementation files To distinguish these types a set of suffixes i used when compiling Cand C program O a r gt or include ies E Tinglermentation es o E Cen Era app ert implementation fs of Ce iT interface doscripiion eae phtes In this tutorial we will use forbade files cc for C file and xp for template definition files Even if we are writing only C code i makes sense to use c 1o force the compiler w treat it as C This simplifies combination of both since Ihe intemal mechanism of how the compiler arrange names in the program differs between both Iangusgee 12 6 1 Compilation Steps The cmpiljon process tikes cc files preprocerses them removing comments add header iles Y and wats them imo ole filet Y Typical sues fr that Tile pe After successful compilation the set of big files is processed by a linter This program combine the Files add necessary libraries Y and creates an executable Under Unex is Sle ie called au if not other specified These sep are used in Figure 12 Te Neic o i With modern compilers both steps can be combined For example our small example programm can be compiled and linked with the GNU C compiler as follows example e is Jast an example name of course 12 6 2 A Note about Style Header files are wed to describe the interface
17. This is the simplest way of strueturing he solution 0 3 problem Each step in the above now expanded an follows A this stage the problem has now been completely solved independent of the language the program is to be writen in IL is now simple to wie the program in any suitable programming language Unfortunately not all problems are so simple wo solve Frequey The simple idea of sequence used above is inulin 1o deseribe the solution of many a Nec problems Consider the following problem Write a program which enters the number af hours worked in a week and an hourly rate of pay of an employee The program shuld output the wage af the employee The employee is paid at tae normal hourly rale Tor the rst forty hours and subsequently at one and a half Umes the hourly rue The problem solution now appears fairly siraighnforward and modeling it on the previous ase algorithm is widen allows However in tempting to expand step 2 the simple idea of sequence i not sufficient This is because if he mamber of hours worked estan or equal vo forty then the final wage i the number of hous multiplied by the hourly rate whereas if more than forty Tour are worked then isthe hourly rate for the first Torty bow and one and a halt times the howl rate for the remaining boues Thus the muth of a condition number of hours lesi than or equal to fory determines which auton should be carried out Such a conditional stutenent ha
18. a space character in the middle hen input will be enminated on that space character The nul character willbe appended w the end of the Sing inthe character array by the stream fumetions H the aring s3 was initialized 36 8 The previous secon then the statement Would set the suing s1 as follows when the string zs rst is entered without the double Nec Note that the last wo elements are a relic of the inition at declaration time IF the siring that is etre is longer than the space available for i in the character array then CHE will just wet over whatever space comes ext in memory This ean cause Some ery strange enos when some of your oiher variables reside ia that space To read sing with several words in it using cin we have to call sin once for each word For example to read ina name in the frm of a Chrisian name followed by a mame we might ie code as follow The user as would just ype the name for example and the output would then be I would be useful if the user of a program could enter the name af the data file that was to be used for input during that run of the program The Following example states how nis may be done It assumes that a ke name Tot an input Tle mast be entered and also a file name for an ouput ile Nec This program assumes that the file names entered by the user do not contain more than 19 character Note how a space character was output alier each iter W
19. all identifiers fot variables and value i an npression involving only constant quantities that gives the constant is value I is not possible to declare a constant without giving it aa initial value Another advantage of using constant declarations is illustrated by the following declaration This defines a constant vatrata to have the value 17 5 however if the Government ater changes this rue then instead of having 1o search through the program for every occumence ofthe VAT rate ali that needs to be done i to change the Value of the constant identifier vat Sate at the one place in the program This of course only works if the constant identifier vatsaa has been used thoughout the program and iN umenie equivalen has never been used Constant definitions are by convention usually placed before variable declarations There is no limit on how many constan declarations en be used in 4 program Several constant identiiers of the same type cn be declared in the same constant declaration by Separating each declaration by a comma Thus Note that it is illegal C to attempt to change the value of a constant 68 General form of a C Program A this stage the programs considered wil fit into he following general format 1 Itrdctory contents fle mina programmer when ven or modified 1 what program does maton declarations Nec variable dectaretons cecal tteents Note that it makes complex programs much easier
20. alsendy been encountered There it was introduced as being a Stemeat which teses a condition and depending on the result of the test carries out one operation or another Thus using a conditional sislement the algorithmic solution above ould be expanded a follows The details of woking out the wage are mot important here what is important is that in describing the solution 3 conditional statement was used Conditional statements ae ofen haractezed by the words M condition then A eise B Neic Which caries out the process if the condition evalustes to uve and otherwise cas fou the process B Al programming languages ave some form of conditional statement The cononal statements available in C are considered inthe following few lessons 6102 Relational Expressions A condition or logleal expression is an expression that can only take the values true or fate A simple form of logical expression the relational expression The following is an example ofa relational expression which takes te value tre ifthe value ofthe variable x is less than the value of the esi y The general form of a relutional expresion is operandi relational aperator operand The operands ean be either variables constants or expressions I an operand is an expression then the expression is evaluated and its value used a the operand The Telatianal operators allowable in C are lt less tan gt greater han Zes than or equal w S
21. an aay as a parameter w a function it is passed as a reference parameter Wiat is scaly passed ie The adress of sft element Since aray are passed by reference thit means that if the function changes the value of an element in an array that is a parameter of the function then the corresponding actual array ofthe call will bave That element changed Tis Neic Though an array is passed as a reference parameter an is not used to denote a reference parameter However it must be indicated to the compiler that this parameter is an array by pending 11 othe formal parameter name Thus 1o declare an array of veal values as a Parameter requires the parameter 10 be specified as follow This the same as normal array declaration but the size of the array is not specified This slot in the following example which earns the average Vale of the fist ements in a real asray M when this function was called the value given for the parameter n was greater than the umber of elements in the actual array replacing the parameter then an incorect result wouid be etamed The function neanarsay could be used as follows An aray can also be an output parameter consider the following example in which the fanetion saaaeray als wo araya opethar 1o produce a third array whose elements are he sum of the corresponding elements in the original wo arraya Neic The function sasar ay could be used as follows
22. an item code of 161432 an order quantity of 3 and a unit price of six pounds fifty pence Assume that the says date will also be entered Wine a C program o enter details of such an invoice and w ouput an invoice which indicates the foal cost of each emt and the total cost of the invoice topether With fall eraits The above details might produce an invoice as follows T Neic A fist atemptat an alg smigh be Assume that there are four programmers availible to implement this program There are four major operations inside the zox loop hence each programmer could e given one operation to implement The best way to do this is 10 use 2 function foreach operation ich programmer caa then be given a precise definition of a function For example considers the operation senter rocora This function must seud in the integer quantities lem number quamtity and uait price ia pounds and pence Hence it has o input parameters and Tour output parameters A definition of the function could then be writen as Toliows Similarly the other functions could be specified as follows Tis neice In terms of these functions the main program could be writen as follows Tis Nec Using the function specifications above the functions can now he written and tested separately For example cotecoct could be writen as follows Totes this function on it
23. by It operates oa a single operand and etn fae if is operand is true and true if s operand i falie The operator and represented by ss tikes two operands and is true only if both of the operand are tue If either operand is false the resulting Value i false ori the final logical operator and is represented by Isls in true if either of its Speranas is true t reurns false only if Borhs operands are false The logical operators can be defined by truth tables as follows Note that F is used for fakse and Tis used Tor tue in these tables No Aae Ort AIA ABAS amp E ABAIB FT FFF FFF TF FTE FTT TEE TET Trt TIT These tables show that mot reverie the truth value ofthe operand that the amd of rwo operands is only tue if both operands re tue and thst the oof two operands it ure if either or both of is operands are true Using these logical operatore more complex Conditions can now be winen M amp has the value 15 and 3 has the value 10 then the expression i gt 20 et 13 gt or is evaluated by evalusting the elation gt 22 whichis true then evaluating the ry Nec relation j gt o which is also true to give true If has the value em the second ton would be false so he overall xeon would be fale IC has 1e valas S the he fit selon woul be fake and he expression sl be ae epee of he tale ofthe second vlan C3 oes nt eve ea he second aon in ht Situation Sin the os enon true nano 11 express
24. by the following properties L tresports atype 2 Irexports aset af operations This ser i called interface 3 Operations of he inerfoce are the one and only access chariot the e s dita 4 Axioms and preconditions define the application domain ofthe type With te fist property it is possible to create more than one instance af an ADT as exemplified withthe employee example Ia the first version we have implemented a list st module and were only able to we one list at a ime The second version introduces The handle as a reference to a list object From what we have learned now the ale in conjunction with the operations defined in the list module defines an ADT List When we we the handle we define the corresponding variable to be of type List 2 The interface wo instances of type Ls is defined by the interface definition file 3 Since he interface definition fle does not include the actual represeniion ofthe handle it eannot be modified del 4 The aplication domain is defined by the semantically meaning of povided operations Axioms and preconditions include statements such 3b An empty list is a st Let fll d2 d3 dN be a list Then Lappend dM ess in Hd 2 d3 N AMI The fin element of a list can only be deleted ifthe istis not empty However all of these properties are only valid due 10 our understanding af and our discipline in using the list module IL is in our responsibility wo use instances of List
25. calculating natal les The Analytical engine for more general calelatins Neic Ada King Countess of Lovelace closely associated with hese projects is Widely regarded asthe first programmer 144 The first electronic computers Eckert Mauchly and von Neumann co develop many of the central ideas for modern compute stems The von Neumann architecture i still he key model CPU memory long term storage communication bus and peripherals int computer were hard wized had to physically exchange cables wo creste diferent programs Ely systems included ENIAC ILLIAC and UNIVAC late 1940 Machines cost hundreds of thousands of dollars requie Tens of thousands ff vacuum bes and mlays huge space requiremens breakdowns frequent The sored program concept a key idea have a system which can use sequences of isiraetions sored internally Alan Turing develops theories of computation the Turing machine Successfully models deseribable computation processes 1 4 5 Transistors replace tubes The next generation of computers transistors replace vacuum tubes Tape dives make long term storage and ete of data racial Improved memory systems allow faster operation and more flexible programming Machines become much smaller faster cheaper and more elable Comptes now practical for rg organizates 1952 CBS computers accurately pdt results of presidential election but reals withbold because announcers do believe them unl
26. function called say caicusse This function would uke the hows worked hnd the hourly rate as input parameters and would ceturn the wage as ouput This funetion is then called to produce the wage when values are available for the hours Worked and the hourly rate The algorithm above could then be weiten Apart from its use in this program the function ca 1ewage might possibly be used in other programs in the fature which required te calculation of wages Another advantage of The ove approach is that if the rules for calculating wages are changed then oniy the fanetion ose need be changed Thus if the solution ofa problem has been neatly encapsulated imo a function which has ben comprehensively tested and debugged then it an be incorporated into subsequent programe This obviously saves much work and Temoves some sources of error Ultimately everyone in an organization could use tis ction in their programs Without even having 10 understand how to actully solve the problem himself or herselt 9 2 The need for functions A rationale for the use of functions has been given above Basically they save work in hat baning solved a problem oce i need not be solved again f there exists a function to Solve the problem given the particular parameters for this instance of the problem In tion the function can be comprehensively tested and hence a possible source af ertor Selina in future programa These reasons are now expanded upon 1 When solving lar
27. lasses Sometimes it makes sense wo only describe the properties of a set af objets without knowing the atl behavior beforehand In our drawing program example Sach bject should provide a method to daw isel on the drawing area However the acessary stepa to draw objets depend on is represented shape For example the drawing routine of a circle is different fom the drawing routine of a rectangle Lets cali the drawing method print To force every draw able object to include such method we define class DramableObjeet rom which every ather class in our example inherits general properties of draw able objects We introduce the new keyword abstract here Itis used 1o express the fact that derived lasses must redefine the properties to full the desired functionali Thus from the svat class point of view the properties ane only specified but not filly defined Derived classes must provide the full definition including the semantics of the properties Now every elass in our drawing program example inherits properties ftom the general drawable abject class Therefore class Point changes 1 Neic We are now able to foree every drawable objet to have a method called print which should provide fianctionality to dra the object within the drawing area The superclass of AN drawable objects class DrawableOhjert does not provide any functionality Tor raving isl IU is not intended to creste objects from i This class rather specifi
28. list However quenes provide acess methods to pur a data element at the end and 10 ger the first data clement frat irat out FIFO behavior Suppose you want to program a list in a modular programming language such as C or Moduls2 As you believe that lite ae a common data active you decide 10 implement it ina separate madale Typically this requires you to write two files the interface definition and the implementation file Wahi ths chapet we wil use a very Simple pseudo code which you should understand immediately Lets assume har Neic ennment are enclosed in Our interface definition might then lok similar to that below Interface definitions just describe war is available and not how it is made available You hide the information of the implementation in The implementation fle This is 2 fundamental principle in software engineering so lets repeat You hide information of the actual implememation information hiding This enables you t0 change the implementation for example to use a faster but more memory consuming algoritam for saring elements without the aed to change other modules of your program The calls povided procedures remain the same The idea of his interface is as follows Before using the list one has to eall dit iniialize to iniiaize Variables local w the module The following Two procedures implement the mentioned access methods append and delete The append procedure needs 4 more desile discu
29. of the Sereen ot H may wrap round on to the next ine Do not rely on either behaviour as ferent computer systems may do things differently Thus Wil print sass tnea on the curent output line and then take a new line forthe next ouput The statement Will display if the user enters 6 51 and 3 24 at the prompt the following output Note that a value written 1o cost will be printed immediately afler any previous value With no space between In the above propru the character sings writen to 052 each od with a space character The statement Would print out the results as Nec Which is obviously impossible to interpret correctly If printing several values on the ame line remember to separate tbem with spaces by printing a siring in between them as folios 6 10 Structured design 610 1 Conditional Control Structures In designing programs i is best to proceed with algorithoniprogram design in a top down structured manner that is by fis recognizing the majar components of the solukon Then expressing Te solution as a sequence of these major components and then expanding The major components themselves similarly Consider the example C program that computes the are and perimeter of a rectangle when a user enters the length n width A possible initial algoritm ys follows where each step is numbered Notice that the idea af sequences been used bere that is that the operations ane eared out in the onder they ae write
30. separate the individual values in the output fie Chapter 11 1 Nee Streams and External Files Streams and External Files 11 So far ul ingust and output has been dane by obtaining data from the input streama cin and Sending ouput to the oput seat cout These reams have been connected to the vl and sereen respectively There ac many situations When thse facie are not sail For example When the amount af data to be entered to a program it very large ar when a program is wo be enseted at a ltr dite with the sume daia This may happen wile developing and testing a program with vet of test data 2 When the data fae a program has beca ced By anther computer program 3 When a permanent recond af the output of a program bs required in all these cases External Files are required Thus if a program sequies a significant amonat od data to be eters then the data can be entered oa a file using a text editor and 1 Nec his file wed as the input medium while developing and testing the program Similarly ouput can be sent toa file so that a permanent recond af esuli s obtained streams In Co data is writen to and rom streams A stream is a sequence of characters connected to a device or to a disk file Telemed to by nae The sreams cin and cout which are connected to the keyboard and the sereen mespecnivey have already been considered When using these seams the fle ke rean ast be incline program
31. this copy of the valu ofthe parameter annot aleet the original actual parameter AN the examples that hve been considered hve wed call by valoe parameters This is because all the parameters used have been input parameters To make a parameter call by value tis specified n the parameter Uist boy giving is type followed by ite name Thus if a parameter is only to be used for passing information into a function and does not have to be rerumed or passed back from the futon then the formal parameter repescning that parameter Should be call by value Nore also hat since the function cannot change the value of a call by value parameter in the calling program strange side effects of calling a function are avoided Tis Neic 9 5 1Purther User defined functions in C The only method used to return information w the calling program was by the function retuming a single value Frequently its necessary to write factions Ihat retum more than ne value For example a function that took a sum of money in pence might have 10 eu the equivalent sum in pounds and pence To allow information to be returned to the falling program C allows iforation to be returned by parameters To allow a meer et 2 value tet be declared to be eallrby eference parameter 95 2 Callby reference parameters Values cannot be returned to the calling program via call by value parameters because the function only operates on a copy ofthe value of the parameters not on t
32. two nz variables to be evaluated as a 1032 expression at least ne of Ihe variables must be converted to oat This can be done by using he east The type sions is used at an operator to give a floating point representation of the variable or expression in brackets Notice that toat o s wil stil evaluate the apression se anne amd only conven ito clone afer the integer division has been performed Other types can be used wo cast values too tnt cx wil remen the value of x expressed as an nc Similarly enar ty Will et the character corresponding tothe value y i the ASCH character set 77 4 Example Program Temperature Conversion Tor Neic The folowing program comens an input value in degrees Fahrenheit to the corresponding value in degrees Centigrade Note how the constant su 13 has been defined ising an expcsion A Constan can be defined using an expesion as long at the operands in the expression are numere constants or the names of constants already defined Also moe that the constant has been given the value 373 8 if it Rad been defined by 5 gt then this would have evaluated to zero an integer divided by an integer hich is mot the ite 75 Example Program Pence to Pounds and Pence The following program converts an input value in pence 1o the equivalent value in pounds and pence Note how integer division has been wed 1o find the whole number of pounds in the value of pence by dividing
33. whether a program should ope gracefully with non existent data afier all why would auser use the program If they hut ao data to emar However a typing errot may lead to the entry af unable data and it is preferable that tbe program should recover graceful from this station rater than fait with an obscure rum time error Ister This program could do this by either checking the sign af the first candidate number entered and terminating with a suitable message if itis negative or could recognize the sition by checking that count is non zero before proceeding w calculate the average Adding various facilities to it ould extend this program for example indicating for each Student whether they have passed judged by some criteria Se the exercises for possible xenon far you wo wy Nec 8 5 6 Example Program Iterative evaluation af a square root Frogenly in solving scientifi problems iterative methods ate used In an iterative method a first approximation to Solution of th problemn is produced then somme method hich improves the accuracy of the solution is used repeatedly uni two successive approximations agree to the accuracy required This process could be described algorithmically as follows A simple problem that can be solved in this way is that of finding the square root of a positive number N atd is an approximation 1o the square root of a uber then a beter approximation mew is given by new a Eon For example aking
34. 14 Sirategies and Representation 2 Object Onened Programming CHAPTER 3 Abstract Data Types 3 1 Handing Problems 5 2 Properties of Abstract Data Types 33 Importane of Dara Structure Encapsulation 2 4 Generic Abstract Data Types 2S Notation 36 Abstract Data Types and Object Orientation 3 7 Implernentation of Abia Data Types CHAPTER 4 Basie Concepts of Object Oriented Programs Aics A2 Object 13 Mesane 44 Summary 4 Relations AS A Kind O lationship 452 A relationship 453 Part Of relationship 454 Hava relationship 16 aheitance 46 Inheritance 4 62 Multiple Inheritance 47 Abstract Classes 445 Template Css 49 Sac and Dynami Binding 10 Polymorphism CHAPTER 5 Introduction to 5 1 The C Programming Langage S11 Data Types 51 2 Satemene 5 13 Expressions and Oporto S14 Raction 515 Pointers and Araya SLG A Fims Program CHAPTER 6 from To C So Hisor of Ce 61 Basic Extensions 614 Dara Types u ds 25 fj 3w 2 3 3 u u M 3 w a aL a a uv as a pi Si 3 s s s 8s es 9 70 Neic 6 12 Functions 62 Fist Object orented Extensions 162 1 Classes and Objects 162 2 Constructors 1623 Destrucion 163 Simple C Progam 64 Variables SReserved words 66 Declaration of variablas 6 IConstants amp declaration of Constant 68 General foem of C Program 69 Input 6 10 Strate Design 610 1 Conditional
35. Coal Sac 16102 Relational Expressions 611 Logical Expressions 6 12 Repetition Control Siractases 6 13 Other forms of Repetition onl Structures CHAPTER 7 The Assignment statement T L The Assignment statement 172 Priority of Operators 13 Type Conversions Ta Example Progan Tenperaure Conversion 11S Example Program Pence to Pounds and Pence Vo Increment and Decrement Operators 77 Specialized Assignment Statements TS Formaning of ouput 719 Example Program Tabulation of sin function CHAPTER 8 Statements ETT if statemen SL iBsamples of if sileman Zhe it else Statement 2 tBsamples of i else statements 12 2ample Program Wages Calculation 1 2 sample Program Pythagorean Triples 1 2 4 Example Programe Area and Perimeter of Rectangle S3Neste i and else statements te switch statement SA AEsamples of switch statement Site whe natement 8 5 1Example while lop Printing integer 85 2Etample while lop Summing Anthene Progen 8 53 Example while loop Table of sine function 8 5 4Etample while lop Average Minimum and Maximam Calculation Neic 8 5 5 Example Progam Student mack processing 5 5 6 Example Progam erative evaluation ofa squate root Ge dru sistement 6 1sample Program Sum of Avmctic Progression 6 2Esample Program Valid Input Checking 6 sample Program Student Mark Processing 2 rite for satemene 8 7 1Example for stinsent Prin 10 integers 8 7 2Etample
36. Data Types and Object Orientation ADTs allow the creation of instances with welldefined peopenies and behavior In bject evientton ADTs are refered oat laces Therefore a ias defines properties ot bjer which are the instances in an object oriented environment ADTs define functionality by puting main emphasis on the involved data eir structure operations as well an axioms and preconditions Consequemily object oriented programming is programming with ADTs combining functionality of diferent ADTs To salve a problem Therefore instances objecti of ADTs classes are dynamically tated destroyed and used 347 Implementation of Abstract Data Types The last section introduces abstract data types ADTs as an abstract view to define propenies of a at of emities Objectoriened programming languages rst allow implementing these types Consequently once an ADT is implemented we have 1 particular representation of it available Consider again the ADT Iter Programming languages such as Pascal C Modala 2 and others sea offer an implementation for it Sometimes it ell ju or imeger Once you ve crested a variable of this type you can use i provided perations For example you can add wo integer E Nec Lets play with the above code fragment and outline the relationship 1o the ADT Jeger The fies line defines throe instances J jan of type Integer Consequently fot each instance the special operation constructor should be c
37. Neic Table of Contents CHAPTER 1 Principles of Programming L1 A quick history of computing K1 Early devices amd algorithms EZT tt mechanical efons EA 3The difference engine EAAThe fist electoni computers E1 STransistors replace mbes 1 The evolution of programing languages 1 Integrated circnits and operating systems Microprocessors and PCs 1 9 The Internet computers and communication EEAO As the search Tor thinking machines 12 Some Remarks abou Programing 12 1 Programming Languages 13 HaadwareSoftae Interaction 13 1 Source Code compiling and execution 132 Runing a program 13 3 Fetch Decode Execui cycle KA Computer software and languages KA 1Computerised problem solving 1142 Sofware types A3 Language types KAA High level languages 1AL6 The Ct programming language 1S Problem solving amd software developement 1 S aSofvare Engineering 1S2 Sofware ie eyele 1S Problem solving press 134 Program development 1S3 incremental developmen 136 Desig and anal 13 Top down design 15 Algorithms 6 Small scale programming management CHAPTER 2A Survey of Program 21 Unstructured Programming 22 Procedural Programming 23 Modular Programming 24 An Example with Data Souci 24 1 Handling Single Lists 242 Handing Muliple Lis 2 5 Modular Programming Problems ng Techniques Neic 25 1 Eaplicit Creation and Destruction 25 2 Decoupled Data and Operations 2 5 3 Mising Type Safety 25
38. Note that the parameter size could have been replaced with any value up to the size that was declared for The arrays tha were used as actual parameters In the example above the alue of 20 was used which means that only the first 20 elements of the aay ee ae Also note that the input parameters and 2 have been declared in the function head as being af type onat r102 Since they are input parameters they should mot be changed by the function and declaring thm as constant arrays prevents the function from changing them 10 7 Strings in C So far the only form of character information used has been single character which are defined as being of ype chax Character stings have also been used in output A new data type is now considered namely the character string which is used to represent a sequence of characters regarded as 4 single dala ilem In C stings of huraces are held as an array of characters one character held in each amay element In addition a special null character represented by 8 appended 1o the end of the sring 1o idea the end of the siring Hence if a sting han s characters then i requises n n element array at least to store i Thus the character i stored in a single bytes Whereas the single character string 3 is stored in two consecutive bytes holding the arate and the oul chante Astin variable lt 3 could be declared as follows Tier Nec he string variable could hold strings of lengt
39. Sometimes ake sense to know that there i a pointer cs avaiable which indicates the invoking object Currently we ned wo cll the set methods 1o initialize a point object However we would lke o initialize the point when we define it We therefore use special methods called 622 Constructors Constructor are methods which ane wed to initialize an object at its definition time We emend our elass Point sach that i initializes a poit to coordinates 0 0 z Neic Constructors have the same mane of the class thus they are identified to be constructors They have mo retum value As other methods they can Lake arguments For example we may wan to initialize a point to other coordinates than 0 O We therefore define 3 Second constructor tiking Wo integer arguments within the class Constructors ane implicitly called when we define objets af their classes With constructors we are able to initialize our objects at definition time at we have requested it in section 2 far our singly linked list We are now abet define a class List aere the constructors take care of correctly initializing its objects M we want to create a point from another point bence copying the properties of one object toa newly created one we sometimes have W tika eae of the Copy process For example consider the class Lt which allocates dynamically memory forts elements If tee want to create second list which isa copy of the first we m
40. The data which ane affected and Toe operations wuch are identified by the problem At an example consider the administration of employees in an institution The bead of the administration comes to you and ask you to create a programm wich allows administering The employees Well this nor very speci For example bat employee information 1 eee by the administration What tks should be alowed Employees are real persons Who can be characterized with many properties very few are Neic Name Size Date of it Shape Socal security number Room number Hair color Hobbies Cor sinly not all of these properties are necessary to solve the administration poblem Only some of them are problem specifie Conseguemily You create 4 model of an employee for the problem This model only impliet properties which are needed to al The requirements of the administration for instance mame date of bith and social Tambet These properes are called the data of the employee model Now you have described real persans with help of an abstract employee There must be sme operations defined with which te adminiswation is able to handle the abstract employees For example there must be am operation which allows you to creste a new employee once a ew person eners the instituton Consequently you have 10 identify the operations thc should be able w be performed on an abstract employee You also decide w allow Accesa othe em
41. a method on isel In our pseudo programming Enguage we could create new objects and invoke methods oa them For example we could we to exes the fact that the integer object should set its value to 1 This is the message Apply method seValue with argument 1 om yoursel sent o objet We none the sending of a message with This notation it also used in C other object oriented languages might use other notations for example Sending a message asking an objeto apply a method is similar to a procedure call in radon programming languages However in object orientation there is view of amonomans objects which communicate wih each oiher by exchanging messages Objects react when they receive messages by applying methods on themselves They also imay deny the exceation of a method Tor example if the calling object is not allowed to Nec execute the requested method In our example the message and the method which should be applied once the message is received have the same name We send setValue with argument It objects which applies setae Definition Message A message is a request to an objec to oe one of ie methods A message therefore contains The name of he method and The arguments ofthe method Consequently invocation of a method is just a reaction caused by receipt af a message This is only possible if the method is actually known to the object Definition Method A method is associated wiih a elass
42. according to these rules Nec 3 3 Import eof Data Structure Encapsulation The principle of hiding the used data structure and to only provide a well defined interface is known as encapsuation Why is i so important to encapsulate de data strctre To answer this question considers the following mathematical example whee ee want to define a ADT Tor complex numbers For te following is enough to know That complex numbers consists of ewo paris ral part and imaginary part Both parts are repesened by real numbers Complex numbers define several operations addition beacon muhiplication or division to name a Tew Axioms and preconditions ase valid 2 defined by the mathematical definition of complex numbers For example i exits 3 etal element for addition To sepe sent a complex number it is necessary to define dhe data structure 1o be used by its ADT One can thnk of at least nwo ponies to do this Both parts ae stored in owo valued array where tbe first value indicates the seal part and the second value the imaginary part of the complex number Is denotes The veal part and y the imaginary part you could think of accessing them Via array subscription r and y Both parts are stored in a two valued record M the element name of the real part is r and that of the imaginary pat is rand y can be obaied with me and Poin 3 of the ADT definition ays that for each aces to the data structuse there must be an operation def
43. al and imaginary parts because the operator is defined outside of the clasts scope However the operator is so closely Teated othe class that would make sense to allow the operato Wo access the privat members Declaring it to be a friend of clans Complex can do this 125 Friends We can define functions or classes to be friends of a class to allow them direct access 1o its private data members Fr example in the previous section we would like 10 have the fanetion for operators to have aces othe private data members real and imag of lass Complex Therefore we declare operator w be a friend of elass Compl You should not use fiends very often because they break the data hiding principle in its andaenemnals I you have to use fends very ofe ie always a sign that iris te to restructure your inheritance graph 7 Neic 12 6 How to Write a Program Uni naw we hae only presented parts of or very small programs which could easily be handled in one fle However greater projects ssy a calendar program should be split into manageable pices ofen called modales Modules are implemented in separate fes and we wil now briefly discuss how modularization is done in C and Ce This discussion is based oa Unn and the GNU C compiler If you are using other constellations the following might vary on your side This Is especialy important for Those who ase using inegrated development environments IDEs for example Borland Cen
44. alled n our example the compiler internally des this The compiler reserves memory to hold the value of an integer and ind the corresponding name to it H you refer tod you actually refer to this memory area which was conse by the definition of Oponaly compilers might choose To initialize the memory for example they might set it 10 O aero The ext ine Sets the value of toe 1 Therefore we can describe this line with help of the ADT notation as fellows Perform operation set with argument on the Integer instance This i writen as Follows se We now have a representation at wo levels The fist level is the ADT level where we express everything Ihat is done to an instance of this ADT by the invocation of defined operations At this level pre and postconditions ae used 10 describe what actually pp n the following example these condos are enclosed in curly brackets Precondition j n where n is any Integer iseti Postconditions 1 Don t forget that we currently talk about the ADT level Consequently the conditions are mathematical conditions The second level is the implementation level Where an semal representation i chosen forthe operation Ia C tbe equal siga implements The ef operation However ia Pascal tne following vepresemation was chosen In either case tbe ADT operation ser is implemented Lats stess these levels a inle bit further and have a look at the line Obviously was chosen t
45. an internal machine language which they execute directly This Tenguage is coded in a binary representation and is very thous to wrie Most Nec instructions will consist of an operation code part and an address part The operation code indicates which operation is 10 be caned out while the address part of the instruction indicates wbich memmory Jocation eto be used as the operand O the incon For example in hypothetical computer successive bytes of a program may contain Operation yan Address Meaning 010101 10100001 toad e129 into accumulator ooon 10100010 al 130 to aceumnlator 10110 nooo Ore claceumalator in location Where cC means the contenus of and the accumulator is a special gister in th CPU This sequence of ode thn adds the coments of locaton 130 to th contents of the accumulator which has been previously loaded with the contents of Iocation 129 and then stores the result in locaton 131 Most computers have no way of deciding whether a ticular bi pariera is supposed to sepresent data or an instruction Programmers using machine language have to keep careful track of which actions they are using W sore data and which locations are to form the executable programe Programming emors which lead wo instructions being overwritten wah data or erroneous programs which uy to execute part of their data are very difficule to comect However The ability o interpeet the same it pattern a3 bath an instructi
46. and outa were closed While some operating systems will do this automatically when your program Ierminates ii good practice 1 always close iles before exiting a propran I this s not done then sometimes not all of The output is written te le M tbe program was to be run again with data from a different file then the only way this ould be done would be to edit the program above and replace each occurrence of save wid the name af the ather input fle This is obviously inconvenient and iis uch ber to allow the user w eter the Dle name at rum time Nic Chapter 12 Extending Classes Extending Classes 12 12 1 Inheritance In our pseu language we formulate inheritance with inher fom In C a colon replace these worda AS an example lets design a cass for 3D points OF couse we want To Nec 12 4 1 Types of Inheritance You might notice again the keyword psc used in the fist line of the class definition its signature This necessary because C distinguishes two types of inheritance public and private As a default classes are privately derived tom euch oiher Consequnl we must explicitly tell the compiler to use publi ehertance The type of inheritance influences the acces rights to elements of the various super clases Using publie inheritance everything which i declared private in a superclass emai pve in the subclas Similarly everything whichis publie remaina east When using private inheritanee the thi
47. ansmers fr programmers wrote C Tim itallws sometimes say wei his which in other languages suchas Pascal are forbidden due to its bad influence on programing style Anyway When used with sme discipline C eas good a language ax iny aher The comment la C is enclosed in Comments cannot be eniad 5 14 Data Types Table 7 1 deseribes the builtin data types of C The specified Size it measure in bos on a 386 PC runing Linux 1213 The provided Domain is based on the Sie Value You in bts information about the size of a data type with the 212952 operator Variabiet O these types are defined simply by peeing the name with the type fost oa long inng very log integer With st rust you can combine several different types together In other languages this is sometimes called a reco sce dates int day oath year Haba The above definition of aats it also the declaration of a structure called aces We can define ier variables ol this ype by referencing the seus by rarae sic date antheDate We do not have 1o maeme racist I we oi the name we just cannot reuse it However if we namme a structure we ean jus derlare it without defining a variable at bout minute second 7 Nec We ane able to use this strate as shown far another Data This is very sila 10a type definition known in other languages where a type i declared pie tthe definition ff variable of this ype Variables must be defined prior 1o their us
48. ape sis Bonetion returning pointer to pe Set scount O7 Tape s name OJ Fonction return peinter to tape ant Coount Vz Tap Kenane O pointer to Ratan retwraag type amt Cecom O Tape nanm F Sanction return reference to fpe ant toowt Oi nC and C you can me the modifier cons to declare particular apts of a variable ar object to be constant The next table 6 2 lists possible combinations and describes their meaning Subsequently some examples are presented which demonstrate the use of Nec Declaration Tipe cone vane lar contort pe constant pate Oe Sant pe same malaes Emnat power to Cosa Sant ipee const name wa suntan te Taher to costae Now lt investigate some examples of constant variables and how to use them Consider the following declarations apain from 1 The following ssigments are valid The following assignments are Invalid When used with references some peculiarities must be considered See the following example program n Nec When compiled with GNU g the compiler issues the following warning Conversion from ont inr vo int A discards const What actully happens i that the compiler automatically creates a temporary integer variable with valu of to which reference r is iniiaized Consequently when changing the value ofthe temporary integer is changed This temporary var
49. be Since the square root of a negative number is not defined in seal arithmetic no attempt Should be made tous this algorithm if the value input is negative Also if the input is Zero which has square root zero the use of this algorithm will lead to division by somthing approaching zero This should be avoided by making zero x special case Hence the program Nec 8 6The do while statement The following example is a version wing a do uhiis statement of the problem considered atthe beginning of the Lesson on the wise statement The program has to cept positive numbers entered by a user ano accumulate their su terminating Whee a negative value is entered Again the accumulator Variable sun is initialised to zero and the first value is entered ftom the user before the do vblestatetent is entered for the first tne The statement beween the ao and the w129 is then exceed before the condition x gt 9 is tested This of course is iferet from Ihe while statement which the oncom i tested before the statemen is exceed This means that the compound satetet between the do and the we 12e would be esecuted at least once even i the wer entered a negative value inky This value would then be added wo am and the computer would await enuy of Tr Nec softer value from the user Thus do ni 2e statements ar mot used where there is a possibility that the statement inside the loop should not be executed The ge
50. be separately available For at reason modular programming lowa grouping of procedures nto modules 2 3 Modular Programming Wit modular programming procedures of a common functionality are grouped together into separate mode A program therefore no longer consists of only one single part IE is now divided into several smaller parts Which interact through procedure calls and which form the whole program as shown in figure 24 Nec tas wesley os va ronsar eestas Each module can have its own data This allows each module to manage an internal state which i modified by calls to procedures of this module However there 15 only one tate Per modale and each module exists at most once in the Whole program aaa Example with Data Structures Progam wae data structures to store data Several data structures exit for example lists tween asray sets bags or queues to name a few Each of these data siructures cun be characterized by thei structure and their access method 24 1 Handling Single Lists You all know singly linked lists which use a very simple scar consisting of elements which are strang together at shown in figure 25 cC a p p Pagare 28 Seat of a singly inked i Singly inked lists just provide access methods to append a new lement to their end and 1o delete the element atthe iront Complex dia siructures might use already existing anes For example a queve can be sacred Uke a singly linked
51. bol is conser 1o be a leter Iis se as the fist character in an identifier tno recornmended though becuse many Ibrary functions in Civ use such iets Similarly the use of two consecutive underscore symbols i forbidden Nec The folowing ae valid identifiers hough using _Presnure i not recommended The following are invalid dentifiers should be chosen to eflect the significance of the variable inthe program being written Although it may be easier to type a program consisting of single charter identifiers modifying or correcting the program becomes more and more difficult The minor typing effort of using meaningful identifiers will repay itself many fold in the avoidance of simple programming errors When the progran is modified At this stage it is worth noting that C is easessensltive That is lowercase letters ae Treated as distinct fom upper case leners Thus the word nain in a program i quite tient om the wond wate othe word 1 65 Reserved words The syntax rules or grammar of C define certain symbols to have a unique meaning Within a C program These symbol the reserved words must not be wed for any other purposes The reserved words already used are nt and vosa All reserved wos re in lower case eter The table below ists the reserved words of Co Crt Reserved Words ana 04 aan ano stand a Nec Some of these reserved words may not be esed as reserved by older compilers Howev
52. by input of a negative candidate number A finst algorithmic description of the required program i Nec utpat aun ject averages A lie though shows that tvo accumulation variables will be required to sum the wo inal subject marka and since an average has to be found the number of student must be counted Initially these sums and te couat must De initialized to zero and in process mava the marks must be added to the sums and the count incremented Including these eats the algorithme description is expanded 1o Sct duject2 average to suna eount Note that this algorithm would fail if the first candidate number entered were negative The statement loop in the nst statement would not be executed and henee oar would retin it inl value af zero This would lead to a division by zero when an Intmpt was made to calculate the averagen It is ofen difficult to decide Whether 2 Program should cope gracefully with no exisen data after all why would a user we the Program if they had no data wo enter However a typing error may lead to the emey of Usable data and it is preferable tat the program shoul recover gracefully from this tution rather han fait with an obscure rumie error Later Thi algoritam could do this Dy either checking the sign of the Tirst candidate number entered and Terminating with a sible message I i is negative or could recognize the situation by checking that count Isnon zero before proceeding to calculate the averag
53. cated memory space of the program and sign a alue to thar location changing the value of the variable in your program Which i tly associated wit that memory location or overwriting the machine code of your program Similarly reading a valne from anrosttanpt2001 might access aval that fas not been set by the program or might be the value of another variable Itis the programmers responsibility to ensure that if an array is declared with elements then to anempt is made to reference any element with a subscript outside the range 0 190 2 Using an index or subscript that is out of range is called Subseript Overflow Subscript veriow is one of the commonest causes of erroneous resus and can fequely caase Very srage and aed 1o spot errors im program 105 Intalization of arrays The initialization of simple variables in their declaration has already been covered An aray can be initialized ia a similar manner In this case the initial vals are given a8 a Tist enclosed in curly brackets Fr example initializing an array 10 hola the es Tew prime numbers could be wnten as follow Note that the array has not been given a size the compiler will make it large enough to old the number of elements inthe List In his case p would be allocated space for seven elements I the array is given a size then this size must be greater than or egual 0 the number of elements in the italian list For example would reserve space for a ten element array but would
54. cer visable en and a boolean variable pase_onsn A variable declaration has the fom ype iene ype specifies the type ofthe variables being declared The Meier it is a list of the nes of the variables being declared separated by conus Variables may be initialised at the time of declaration by assigning a vale to them as in he following example Which assigns the Value O to the integer variable couse and the value 010 to the seal Yariable sun The character variable enis initialized with the character 7 2 3 and Product huve no initial value specilied s0 the program should make no assumption hou their contents 67 Constants and the declaration of constants Oten in programming numerical constants are used eg the value of a It is well Worthwhile w associat meaningful names wiih constants These names can be associated With the appropriate numerical value in a constant declaration The names given 10 Constants st conform ote rules fo the formation of identifiers as defined above The following constant declaration Tn Nec defies an integer constant ays_tn_year which has the vale 365 Later in he program The identifier says_sn yess can be used instead of the integer 365 making the program far more readable The general form of a constant declaration i const ape constant value s type is the type of the constant eanstantidenifier is the identitier chosen for the constant which must be distinct drom
55. ction am objectis destroyed for example by leaving is definition scope the destructor af the corresponding lass invoked H tnis class is derived rom other lasses their destructor are alno called lending to a recunive call chain 12 4 4 Multiple Inheritance C allows a class to be derived from more than one superclass as was already briefly mentioned in previous sections You can easily derive from mor than one cass by peeing the supe classes in comma separated list We will not use this type of inheritance in the remainder af this tutorial Therefore we WiN mot go inno further detail here 12 2 Polymorphism Inour pseudo language we ane able to declare methods of classes to be virtusi 1o foree Their evaluation to be based on objet content rather than objet type We ean aho Se hisin Cs has DrowableObject defines a metio printf which is virtual We can derive from this elass other classes Tm Nec Again prin is a vial method because it inherits this propery froen Drwabde Objet The function display which is able to display any Kind of drawable object can then be defined as 7 pipart ayena neat When using virtual methods some compilers complain if the corresponding clas destrcior not declared veal as well This te necessary when using pointers 10 Minal subclasses when it is time to destroy them As the pointer is declared 3s uperelass somally as destructor would be called Ifthe destructor ix Virtual th
56. ctor initializes the 2D coordinates x and _y 1o O zero AS Poimt3D is only derived from Poin there are no other constructor cls and the body of Poin Denat in const int const int is executed Here we invoke methods se and sei to explicitly overt the aD coordinates Subsequently the value ofthe hid coordinate This is very unsatisfactory as we hive defined a constructor Poi which takes wo argumens to initialize its coordinates 10 them Thus we mast only be able 10 tell ut instead of using the defali constructor Point the parameterized Poulos int const ini should be used We can do dhat by specifying the desired constructors afier a single olon just before the body of constructor Points DY M we would have more saper classes we simply provide their constructor calls as a comma separated lis We also use this mechanism ta create contained objects For example suppose that class Part only defines a constructor with one argument Then t0 ewe ereat a objet of class Compound we must invoke Par with st argument This dynamic initialization can also be used with built in data types For example the erste of class Point cold be wien as Tm Nec You should use this initialization method as often as possible because it allows the compiler vo creste variables and objects correctly initialized instead of creating them with default value and to use am ational assignment or other mechanism to sts value 12 4 3 Destru
57. d remember how they together For each atb poblm divide i ino ill anaes problems Continue subdividing unl each ie problem is small enough to be easily solved Solving collection of smal problema thus allows u to selve one much larger problem Experience wil make you mare and more adept at this division process Neic 1 57 Algorithms Once youve divided a problem into its logical sub problens and thought out a solution toeach we can Turn this no an algorithm Algorithms can be writen as a soguence of ordered aurnbered stepa Stepa numbered athe sarne level are intended to De performed in sequence Substeps can be induced corresponding to the sub problems Ex ying 1o pe lot 16 Small scale programming management By programming in the small we mean programs writen quickly usually by a single individet and for which low design and documentation standards are acceptable BY design or circumstance many projects during tides academie yeas seem to fall into this category This is usually only the case if the sofware has a short expected Me span several months or less does not perform any critical functions and is nly going to be sed by the developer o by tolerant experienecd user For programming in the Small many developers waditionally produce lile Gf any decumenaion beyond the commenting in the code and perhaps a short user manual or help facility There are still a mmber of methods we may use to produce quality co
58. de 1 C comment can include and can span over several lines 7 MTA Tiis is the C style comment until end ine 1 C you must define variables at the begining af a block C allows you w define variables and objects at any positon ia a lock Thus variables and objects should be efine where hey are wed Nec 6 11 Data Types C introduces a new data type called reference You ca think of them a if they were lasso real variables or objects As an alias cannot exist without its conesponding real part you cannot define single ferences The amperiand 4 i used to define Teference For example References can be used function arguments and return values This allows t0 pass Parameters as reference o to return a hand toa calculated variable or object The tsble Glis adopted from land provides you with an overview of possible declarations I is not complete in that it hows not every possible combination and some ff them have not been introduced here because we are not going to ie tnem However These are the ones that you will probably use very ote Declaration nomeis Example apes See cout ape name ll open arrar pe are count Cr e e e e fname 0 mamo 1 namo oe Tame vay pointer to tape EE E E E Tape am Ti open array of pointers to pe See teou Ip tape Coane pointer to pen aay of type ant_Coceunt TT r E seen pe et Root Tape natwe une ecw pe ant count Or T
59. de hese wll become even more important in Ister semesters When you start working on team projects L61 Sma project planning and organization There are two common approaches to sal informal projects Working to a specifie poal Working oa specifie time frame In the ist case there is an exact goul for the software capabilities and we work on the software umil that target is met In the second cae we have a set of goals and quails but a fixed time fame so we altain as many of the goals and s high quality as possible inthe alld Ume A rough breakdown of th time spent on smal projects is kely 0 look something Hke this 10 184 of the total tine is spent on denying exactly what the product capabilities shoudl be and planning the project 40 50 ofthe une is spent on design and implementation 25 30 ofthe ime is spent on testing debugging and refining Nec 10 184 of the time is spent on documenting Throughout your computing coursework you encounter ways to effectively identify and record product requirements cary ow design and implementation conduci appropriate Verification and validation and adequately plan and document software Many of the Techniques discussed will be overkill for smal projects In this opening section we will discuss some of the common design ideas that shouldbe followed even on the smallest of programs Perhaps the most important rale of thumb sto wate down everthing Keep a Simen record of Al
60. dependi on how the Ceeresponding author has decided to understand it Anyway within ihis tutor the arrowed line is always directed Towards the super class In te following sections an anmaid arrowed ie iadiets inbei on 4462 Multiple Inheritance One important object oriented mechanism is multiple inheritances Multiple inheritances do mot mean tat multiple subclass share the same super class Tt also does not mean That sels can inherit from a class which el is a subclass of another class Mule inheritances mean that one subclass can have more shan ne super class This enables The subclass to inherit properties of more Ihan one mper ciat and w merge thei properties As an example consider again our drawing program Suppose we already have a class Siring that allows convenient handling of text For example it might have a method to append eee test In ou program we would like to use this chass to add text to the Possible drawing objects I would be nice to also use already existing routines such as Neic smovet to move the text around Consequently it makes sense to let a daw ale ext have 1 poi which defines ins location within the drawing area Therefore we derive a new lise DrawableSiring that inherits popes from Point and Siring 15 uses ia Figue 62 Point Sting DeawatteSting gue 2 Der sleigh ts gers of Poist and Siring In our pseudo language we write this by simply separating the mail super classes by We can u
61. e Adding various facilities to it could extend this algorithen for example indicating for each Student whether they have passed judged by some criteria See the exercises for possible extensions for you 1 Tos Nec 613 Other forms of Repetition Control Structures The while statement wed above executes a statement while some condition remains uue Sometnes it is more natural o repeat something unti some condition becomes trae The repetition portion of the irst version af the algorithm could be writen in the alternative form Mihis version is executed using some positive value terminated by a negative value then it has exactly the same effect as th version using the while statement However behaviour is different fs negative number ix ered first In the repeal sistemet the termination condition is tested afer the body of the loop has been executed onee Hence in this example the negative value entered first would be processed giving a result When none was expected and then another emy value would be expecied Hence the Tepeat ati statement cannot be easily used in situations whare it might not be necessary to eccute the body af the loop In this case it it better 1o use the while statement which Tests a continuation condition before executing the body of the lao Another form of repetition control is ofen regu that is 1o repeat some statement a Known numberof es This can be done with a while statement Kor example Wo execul
62. e if x i3 positive and s if x is negative Using this function the test cull be writen which solves the problem above In genera if uying to find if two quantities are within Some tolerance of each other then test th absolute value of the difference berween them against the tolerance However there is another difficulty with the above Consider the following approximations Exact value Approximation 11d o 02 Which of these approximations ithe most accurate They both have an absolute errar of 0 1 but in ome case the error is 0 1 of the quay being approximated and in the other it is 100 of the quantity being approximated Thus if these approximation were used 133 Multiplying factor in tbe next stage of a computation then in one ease the answer would Dea semal fraction lager than it should be whereas in the other case the answer would be twice what it should Be Ths the velative size of the error with respect W the quantity being approximated is important 1n the square root problemi i was 0 000001 with Square 101 001 then wo successive approximations 0 0018 and 0 0108 would have a diference les than 0 0005 and hence 0 00108 would be accepted as a resul However This result Would be 88 in error Hence it is alway safer 1o test the slave error against the tolerance thin ensures that ress of different sizes have the same number of Significant figures correct Hence if tee significant figures were required in the result The test should
63. e Skseucor of the actual referenced object called and then recursively all destructor af ite superclasses Here is an example adopted from l Using these classes we can define a palette s follows palertalai nau Rady Dynanicaliy create a now Red object The newly induced operator naw crestes a new object of the specified type in dynamic memory and returns a pointer to it Tous the Girst new etme a pointer 10 an allocated bject of elass Red and assigns othe Best element of array palene The elements of alee are pointers to Colour and beanie Red i a Colour he assignment i valid Tru Neic The contrary operator to nis denote which explicitly destroys an object referenced by the provided poise If we apply setete tothe elements of palene the following denrctr calls happen The various deuruetor calls only happen because of the use af virtual destructor I we would have not declared them vital each aozet would have only called Colour Because plete is af type pointer to Colour 12 3 Abstract Classes Abstract classes are defined just as ordinary classes However some of their methods are designated to be necessarily defined by subelases We just mention Their signature including their retum type name and parameters but not a definition One could say we omit the method body or in oiher words specify nothing This Is expressed by Soyo alr emit spats This class definition would fo
64. e These definitions must occur before any statement thus hey form the topmost part within a statement tact pe Desripiion S Domain de eal dae T TTET terore Char dove in singlo Te Tak peor e jae sion toner TE ign igor a PET Toar Floating poki a fea T0 To Sinod Tong Tg ag Seat Tung integer Tart She ese unsigned dar Vaigaad char T acter SO Emiel m ma ag Gea a Toa T A R A 1 Tong integer aad ay Visi stare T Table Bala ype 51 2 Statements Neic C defines all usust Now control statements Statements are terminated by a semicolon We can group muliple statements into blocks by enclosing them in curly bracken Within each block we can define new variables The or statement is the only statement which reslly differs from zor statements of sher languages AlL other statements more or less only difer in Weir syntax What follows are wo blocks which are totally equa in heit functionality One uses the ste loop While the other he roz variant To understand this you have to know that an assignment is an expression Nec E Ta 1 Tene carat ink Ao a e Ea cane stacmant th svitek Taine Oily sed i boops to cout WE wat Joop inured EJ Fzecote simt as longa op k TRTE Faile cerd Fee A Tis ara OF TS ut whore the fst espr is the iitiazation tre second expr inthe condition and the
65. e a Statement n times could be implemented as follows There are several things that the programmer has to get right here the initial value of count the condition and remembering to increment cout inside the Loop body I would Be simpler to wea construct like Many loos fall into his simple category The following problem identifies a related fomm of repetition control structure Write a programa to enter a value fo n and output a table of the squares of the numbers fromm to An algorithm to solve this problem could be writen as follows Nec Mis normal in the formas repeat times and for i taking values frm start 1 finish 0 mot execute the body of the koop ifn ia zero or if te start value greater han the finish The most basic of sepetition consol structures is the while control structure since all the hers can be simulated by i However the others are useful in some cases particularly the for control ste They all have equivalents in C Nic Chapter 7 The Assignment statement The Assignment statement 7 4 The Assignment statement The main sttemeat in C for canying out computation and assigning values m Variables isthe assignment statement For example the following assigament statement Nec assigns alf he sum of 3 and to the variable sverage The general form of an ssigment statement is resl expression The expression is evalusted and then the value is assigned to
66. e conesponding value of x is clelated asa function of This is preferable 10 the following The problem withthe above is hat lain point variables are not beld exactly thus Ot night be represented by something slighrly larger than 0 1 Then afier continually adding 01 to x the fanal value that should De 1 6 may actually be something like 1 60001 Tas the test x lt 2 5 would fail prematurely and the last line of the table would not be printed This could be corrected by making the test lt 3 005 In general it is probably best o use integer variables as control variables in far loops 873 Example Program Student Mark Processing 3 The program from previous section could alto be modified to use the zox statement 10 enwel the loop This canot be dane witout changing the specification of the input dats I the specification was changed so that the nomber of students was entered before the examinon marks then a zor statement could be wed as fellows dnt pumau subsea subject averages T Nec Note that if zero or a negative number is entered for the number of students then this program will fait an atempted division by zero will be encountered why This could De fixed by puting in a validation check on the number of students When this is entered bythe user 8 7 4 Example Program Generation of Pythagorean Triples tee A Pythagorean ile is a set of ee integers Pand sich that Suha mon triple c
67. e it all bu an ication such at night be output This is vital if a listing of ress is to mean anything at a future date 8 24 Example Program Area and Perimeter of Rectangle An algorithm which given two value for the breadth and height of a rectangle would ouput the area and perimeter of the rectangle However depending on whether the Breadth and beigh were equal or mot different messages world be output indicating whether i was a rectangle or a square A suitable algorta for this would be This algorithm is then easily converted into a C program as follows Tm Nec Note how portions ofthe algorithmic description have been used as commons within the program Remember that successive value sent othe out ates soue will each be printed immediately after the previous output value Hence in the program above the printing of the actual values Tor the area and perimeter will be printed directly afler the Rta sing on the same line I a new line is required then send The end of line marker sna to coue 83Nested if and if else statements The 1s oise sateen allows a choice to be made between two possible ahernatives Sometimes a choice mast be made between more than two possibilijes For example th Sign funtion in mathematics returns 1 if the argument i less hap zero returns L if the Argument is greater tban zero and returns zero ifthe argument is zero The Following C Sement implemente this function This is an t e 1s s
68. e leftmost element one successively visits the right neighbor tna one reaches the Last element However more complex dana sractres such as Wees fan be traversed using diferent strategies Even worse somtimes traversing satis depend on the particular content in whieh a data scr is used Consequently takes Sense to separate the actual repeesenion or shape of the dala structure from its iaversing siratogy What we have shown withthe traversing strategy applies to other srstegies as well For example imention might be done such Ihat an order over the leet is achieved or not Neic 26 Object Oriented Programming Object oriented programming solves some of the problems just mentioned In contrast to The other techniques we now ave a web of inleracting objets etch house kaeping 18s own state igure 26 Pure 24 Oo hd ROPE OORT ON TTA sening mesages ta each Consider the multiple ts example again The problem here with modular programering i that you must explicidy create amd destroy your lt handles Then you use the procedures of the modale t modify each of Your handles In contest to that in object riemed programming we would have as many list objects as needed Instead of calling a procedure which we must provide with the correct ist handle we would directly send a message to the list object in question Roughly speaking each object implements its own wel allowing for example many lists 1o coexist Each bject is re
69. ea bow to wit such rounines Similarly a programmer working ia commercial applications might kow very te about how an efficient soring Tounine can be implemented However a specialist ean write sucht routines pace them in a publie brary of functions amd all programmers can benefit Trom this expertise by being able to we these efficient and well tested functions Before looking at how functions are implemented in C tbe use of the matbematicl fanetion routines supplied in Cs considered 9 3The mathematical function library in C The functions sin and zans have alseudy been used in programs in previous Lesions For example occured This sateen used in cain as a call of the C function with the name in whieh returns as ts value the ine of the angle in radians which is given as its input Parameter Qn tnis ense te variable reason In dhis use of function there are no output Parameters the single resul that the function produces i retumed othe calling program Tia the name of de function Some of the mathematical functions available in the C mathematics Library ane listed Below Soon tx inverse cosine 1 lt x lt 1 renuens value in radians in range O to PI range 01o PL tantx inverse tangent returne valie in radians in zange PUD to PI2 ais inverse sine 1 lt lt returns value in radians conca returns cosine of x x in radians 1 Nec sinta retums sine of in radians an retums tan
70. ed by the development and target systems The Language should be appropriate forthe Kind of problem being addressed The programmer needs fancy in the language 14 2 Software types Software is ofen classified into two broad groups Systems software 1 Used Tor managing the hardware and controlling user acess toit Nec Aims at making the system more efficient easier to use more reliable te Applications software vo Sotware actually initiated by the user to solve a problem or achleve some ed Includes word processing databases email web browsers games ete In career terns programmers often specialize in one or the ather but the development and problem solving skil for bth ar simular 143 Language pes There are many different programming languages divided into categories such as Machine language Binary sequences Os and 1 s which represent an instruction in the control logic ofa specifie CPU type Assembly language Mnemonies corresponding to machine language eg 258 oecovr instead af 2100112010009000 High level Language 2 Insiructions corresponding w a common kind of solution step eg ve ite 12 to print out the value of x Lower level languages closely reflect a machines hardware characteristics Higher Mevel languages come closer to natural Language solutions 144 High evel languages Are meant to correspond roughly to the way humans describe solutions Are more abstract than low level lan
71. ed names would be ambiguous However if the Language would take the parameter of te Function into acount would work Thus functions or methods are uniquely identified by 2 The name of the function ar method The types af is paramerer ist Since the parameter ist of both is Nul fanetions fer the compiler is able to figure out the correct function call by using the actual types of the argument var i integer Sare real o ho AF GaN then Use Nalin 7 iF daulle then Use sales 47 Definition Polymorphism 2 Wa function oe method is defined by the combination of is name and the list of types of its parameters we speak of polymorphism This type of polymorphism allows ws 10 reuse the samme mame for Function or methods as long ss the parameter Ist differs Sometimes this type of polymorphism scaled overloading The lst type of polymorphism allows an object to choose corect methods Consider he function move again which takes an object of class Point as its argument We have used this function wits any object af derived classes because the selon holds Now consider a function displ which should be used To display drawable shjects The declaration ofthis Tunetion might ook ke this display DrawableObjeet o primo Nec t We would like to use this fenton wih objet af classes derived from DrawableObject Cicle cle Pot point Rectangle arctangle displaylapoin 7 Should invoke agin ris 7 Gs
72. ed that all output would be formatted using the default setings The default setumgs print integers uing as many characters as are required and eal values are printed vith up to six decimal digits ome compilers give six digits afer the dial poini Consider the following portion of C This portion uses a construct not covered yet namely a tor statement The or statemen is used for implementing oops and will be Covered later The stntemem staring with zor has the effet of executing the statements between the braces 1 a5 1 takes th values 1 2 3 and Neic then ouput follows might be produced This it very untidy and dificul o read it would be preferable if it could appear as fallow Wit the least significant digits of the integers aligned and the decimal points in the ea umber aligned Iss possible to achieve this degree of control on the output format by ing output manipulators Before looking at manipulators selentifle notation for the display of floating point umber is considered Scientific notarion allows very large o vety small numbers to be Simen in a more convenient form Thus a number like 7453000000000000 i Denier 6 7453 x 10 winen as and a number Nike 0 0000000000001245 is bener writen as 1245 x 10 8 Ct allows thi type of notation by replacing the tent the power of boy e or E Thus the above numbers could be wrinien in C as 67483016 and 1215013 These forms can be used in writing constants in C and in inp
73. emplate class List loks like any other class definition However the fst line declares List to be a template for various ypes The identifier T is used as a placeholder for an actual type For example append takes one element as an argument The type of w Nec this element will be the data type with which an actual list object is created For example we can declare ist object for apples if a definition for he type Apple exist Appie anappias Sn seoias teen nosbtonie The first line declares apples wo be a list for apples At this ine the compiler uses the temple definition substimunes every occurrence of T with Appie and creates an actual lus definition for it This leads to a lass definition similar to the one that fellows clans List situs Data structure needed to implement 7 Pet methods ippen Apple element Apple st Apple seien oi moret This sot exactly what the compiler generates The compiler must ensure that we can create multiple Ist for different types st any Ume For example we need another Uist for say pears we can write Li fot Apple appleL ist List for Pear partist In both cases the compiler generates an actual class definition The reason why both do ot conflict by their name is that the compiler generates unique names However since this is not viewable to us we dont go in more delai here In any case if you declare just another list of apples the compiler can figure out t
74. endous disadvantages once the program ges suffieiemtly large For example if the same summet sequence is needed at diferent cations within the program the sequence must be copied This has Jead to The idea to exact these sequences name them and offering a technique to call and return from these procedures 2 2 Procedural Programming A procedure call is used w invoke the procedure Aer the sequence is processed fow of control precedes right afler the position where the call was made figure 2 2 mapapa pose t 1 e a Nec Introducing parameter as proceduts of procedures ub procedures programs ean now be written more structured and error Iree For example i s procedure is corset every time itis used i produces corect results Consequently in cases of errori you can marrow your such to those places which are not proven to be corect Now a program can be viewed as a sequence af procedure callt The main program is responsible qo pass dara to the individual cal the data is processed by the procedures and onee the program has finished the resulting data is presented Thus the flow of daa an be lusts hierarchical graph a reas shown in gure 2 3 for a program with bo sub procedures sexo Pure Pct pone Tae mai ogame eal ocean hands over To sum up Now we have a single program wbich i divided ino small pieces called procedures To enable wage of general procedures o groups of procedures also in other Programs they must
75. er with a final mark for each subject The final mark in each subject is 1 af the examination mark plus 3 of The coursework mark The average final mask far each subject soul also be output End Ta Nec input is to be signaled by input of a negative candidate number A fist algorithmic description of the required program is Shtput sanjac averages A lite though shows that nwo accumulation variables will be required to sum th two final subject marka and since an average has to be found the number of students mst be counted Initially these surs and the coumt must be initialized to zero and in process ravaa the markas must be added to the sums amd the count incremented Including these features the algorithmic description is expanded 1o sot supjuctt average ta sund eoune Sct dumata average to suna eosnt Sttpue aumjece average tpu subjecta aversa This is then easily translated into the following program the main function only s listed imt tiain tinia fanai subject marke fine muanis aabavzs f subject averages ary Se Ghat SS SSundeee avraga 1a SS dubav Note that this program would fai i he first candidate nue entered was negative The sement loop in the n216 statement would not be executed and hence couse Would ein inal value of zero This woud lead w a division by zero when an aiempi was made to calculate the averages I is ofen dc to decide
76. er you would do well to avoid their use Other compilers may ad their owa reserved Words Typical are those wed by Bound comps for the PC which add os Tar noge el and pate Notice that ain is nar a reserved word However this is a fairy technical distinction and for practical purposes you are advised 1o ent natn cio and cout as if they were reserved a5 well 66 Declaration of variables In C as in many other programming languages all the arabes that a program i soing w use must be declared prior to use Declaration of a variable serves nvo purposes M associates a type and an identifier or name wid the variable The type allows the compiler 1o Interpret statements correctly For example in th CPU the instruction to add two integer vales together is different fom the instruction to add wo Nosting point values together Hence the compiler must know the type of The variables so it can generate the correct add inuruction Ik allows the compiler 1o decide how much storage space 1o allocate for storage of the value associated with the identifier and 1o assign an address for each Variable wich can be used in code peneraton For the moment only four variable types are considered namely int float boal and har These types hold values as follow ime aril can represent negative and positive integer values whole numbers Theresa limit on the size of value that can be represented wbich dependi on the numberof bytes of storage al
77. es Properties which must be defined by every derived class We sefer to this special type of inter abstraer classes Definition Abstract Class A class A is called abstract elass if it it only wed at a Superclass for other classes Class A only specifies properties It is not used 10 ree bees Derive lasses must define the properties of A Abstract classes allow us to stacture our inheritance graph However we actually dont Sant to creste objets fromt hem we only want to express common characteris of a Metaf inses 48 Templat Class When defining a class we actually define a user defined type Some af these types can operat on other types For example there could be sts of apples list of cars sts of complex number of even Hisis of lis AL the tine when we wrie down a class definition we must be able to say that tnis class should define a generic type However e don t know with which types the class will be used Consequentiy we must be abie define he class with help of a placeholder to wbich we sefer av if itis the type on hich the class operates Thuas the class definition provides us wiih a template of an etl class The actuat class definition is created once we declare a particular object Tats ilustrate this with the following example Suppose you want to define list elass which should be a generic type Thus it should be possible to declare list objects for ples cars or any other type The above t
78. es are deawn using rectangles Their name always Stars with am uppercase letter The arrowed line indicates the direction of the relation Tence it is 1o be read as Circle is A kind of Point 45 2 15 A relationship The previous relationship is used at the class level to describe relationships between two Similar classes If we creste abjecte af two such clases we refer to their relalionahip a5 an in s elionhip Since the clas Clea kind of class Point an instance of Circle say a circle is point Consequently each cicle behaves like a point For example yot in move points in auction by altering the value of x Simul you move circles in Thin direction by altering teiz 1 value Figure Sse this relationship In hs and The following figures objects are drawn using rectangles with round corners Their name aly consis of lowercase leer Came e al pee Nec 45 3 Part Of relationship You sometimes need to be able w build objects by combining then m out of others You already know this Irom procedural programming where you have The structure or record cnstric to put data af various types together Las come back Wo our drawing program Yon already have crested several classes Tor the available figures Now you decide that you want w have a special figure which represents your ow logos which consists of a irele and tangle Le assume that yon already ave defined a clase Trample Ths Your logo consists of t
79. et Tom rie Chay mas Tom git Tap 2 Pty cast Bea rit 7 Dertener apentor a right I Aires operator om rit Tas cof operon fan ra F 3 atipication operator Tom kit I Dirisio opera 3 Modo operator Tom eie 1 Addita operaio om kt 7 Piractbu operator N Sei Si peter Tom eit 3 ane operator Tro IE 6 Lomen than operator om kft 6 ower ar eal oper ar Go kt 6 estr than operator Tom ett 6 Gheatr orequal operator Tom kit T ial operator Tom kt 7 E Tom ki EE A Tom ki 7 inary XOT Tom ett 10 Binary OR fiom kre TE P Boles Tom ki ii 2 ones O Tom et i I Conditional parame Tom rie Ti Asigamen opr Trom right z str sant OPT ho C3 Ts Crm per cm ale Op he increment operators and Tean be explained by the following example If you have the following statement sequence Nec you can use the pre increment operator iia if you have the following order of saeco you can use the post increment operator Thus the prince operator fist increment it s associated variable and then ears the new Value Whereas Ihe postincrement operator first returns ihe value and then Increment iu variable The same nules apply 10 the pre and post decrement operator Function call nested assignments and the incrementkdecrement operators cause side Hise when they are applied This may introduce compiler dependencies as the evaluation order in some situations is compiler dependent Consider the following
80. f a class definition as a stetur definition with functions or mets Additionally you ean Specify the acces ighas ia more detail For example z and y ae private became elements of clases are private as default Consequently We explicitly nast swich the ceee righs to declare the following tobe publie We do tat by using the keyword punata followed by a colon Every element following this keyword is mow accessible from outside of the ls We can switch back t private access rights by starting a private section with private This 1s possible at ofen as needed g Neic Recall that a structure struct is a combination of various data elements which are accessible from the outside We are now able to express structure wih help of a class there al elements are declared to be public This is exactly what C does with stroet Structures are handled like classes Whereas elements of classes defined with cise are private by default elements of structures defined with sence are publie However we can also use private 10 sich 1o a Private section in structures Lats come back to our class Point Is interface starts with the public section where we define four methods Two for each coordinate to set and get is value The set methods are only declared Their actual functionality is stil to be defined The ge methods havea fanetion body They are defined within the class or in other words they are inlined methodi
81. for statement Print able of sine function 5 7 3 Example Programs Student Mark Processing 3 1 7 4 Example Program Generation of Pythagorean Tapes CHAPTER 9 Functions 9 1Top down design using Functions 912TH ned for functions 9 3The mathematical union ibay in Cos 9 4 Introduerion to User defined functions in C3 9 4 1Functions with vo parameters 9 4 2 Functions with parameters and no tur value 9 4 3 Functions that eu values 9 4 3 Example function sum of squares of nage 9 4 3 2Example Punction Raising Wo the power 9 5 Calbyvalue parameters 9 5 1Furtber User defined functions in Co 9 52 Call by seference parameters 9 512 Example Program Invoice Processing CHAPTER 10 Arrays 10 1 Whats an aay 102 Amaysin Co 103 Declattion of Avy 10 4 Accessing Array Elements 10 5 Initialization of ray 10 5 Example Program Printing Outlier in Dats 10 5 2Example Program Test of Random Numbers 10 6 Arraya as parameters of functions 10 7 Stings in C 10 1 Sting Oupa 10 72 Siring Input CHAPTER 11 Streams and External Files 11 ISweams 11 2Connctng Scans to Exiemal Files 11 Testing for end of file CHAPTER 12 Extending Classes i 161 te 1a 166 Nec 12 1 Inberitanee 12 1 1 Types of Inheritance 12 1 2 Comstruenion 1213 Destruction 12 1 4 Mauttiple Inheritance 12 2 Polymorphism 12 3 buat Classes 12 4 Operator Overloading 12 5 Frends 126 How to eke a Progam 12 6 1 Compi
82. g expressions is that of onder af evaluation Should be evaluated by performing the multiplication fint or by performing the addition fst Cs solves this problem by assigning priorities to operators operators with high priority are then evaluated before operators with low priority Operators with equal priority are evaluated in et 1o righ order The priorities af the operators seen s0 far are in high 0 Tow priority onder Neic Tas te evated iit had been writen as because the has a higher priority than the I the was to be evalusted fist thes Brackets woud need toe used as fellow M in any doube use estra brackets to ensure the correct onder of evaluation H is als important to note that two arithmetic operators cannot be written in succession tue brackets 1o avoid this happening 7 3 Type Conversions The rules stated above mean that division of integers wil always give an integer result IF Ihe correct lat result is required then the compiler mast be forced 1o generate code that evaluates The expression as a roat I either ofthe operands i a cone then itean be expressed as a floating point constant by appending a o to it as we have seen Thus assuming hts an oe variable 1 5 does mot pive the correct reciprocal of n except in The station 5 2 To force the expression 1o be evalusted 3s a ating point expression This solves the problem when one of the operands is a constant but 1o force an expression involving
83. ge problems it is usually necessary to split the problem down intoa series of sub problems wich in vurn may Be split imo further sub problemns ars Nec ete This is usualy called a top down approach This process continues uni problems become of such a size that single programmer can solve them This Top down approach is esensial the work has to be shared out between a team of programmers ech programmer ending up with a specification Tor a part of the Sate which is be writen a3 a funetion ar funtion While writing a single function the programmer is able to concentrate on the solution of tnis on problem oniy and is Thus mane likely to be able 1o solve the problem and make lee errors This function can mow be tested on is own for correctness 2 Ins particular organization or industry 1 may be found that n carrying out the top down approach some tasks occur very frequently For example the operation al sorting a Dle of data imao some order occurs freqealy in data processing applications Thus a brary of such commonly used functions can be built up and rrsed in many diferent programas This obviously saves much work and cue tdown errors if sch functions have lead been weli tested 3 There are many very specialized problem areas not every programmer can know every area For example many programmers working in scenic applications vil frequently use mathematical function routines like sine and cosine but Would Bave no id
84. gent af x in radians Sxin exponential function e to power x ogi aug of x base e x gt 0 252260 square root of x x20 taba absolute value of x oe largest integer not greater than x 64260 smallest integer not ess than x In al these functions the parameter x is a floating point value The x is used as a format parameter that s it is used 10 denote that a parameter is required and 1o allow the effect I tne function to be described When the function is called Dhen thi Toral parameter 35 replaced by an actual parameter The setus parumeter can be constant 2 variabile or an expresion An expression may include a eall of another function These functions are called by quoting their name followed by the actual parameter enclosed in rounded brackets for example 2 The function call ean then be used nywere in an expression tiat an ordinary variable may be used Hence the following examples The file nann must be include in any program that is gaing 1o use any functions from ths library ratissa also defines some constants which may Be wed For example 1 can be used for and c canbe used for 9 4 Introduction to User defined functions in C C4 allows programmers to define their owa functions Fo example the following is a definition ofa function Which given the cocorstes of a point tay Wil retum i stance from the origin Tis Neic This function has two input parameters real values x and y and
85. greater than or egual to ot equsls Note that equality is tested for using the operator since is already used for assigning valves to variables The condition is true if the values ofthe two operands satisfy the relational operator and fale eerie Examples using Relational Operators Obviously depending on the values of the variables involved each of the above relonal expressions is true or false For example if x han the Value 3 y 66 3 w Neic 10 the last expression above evaluates to true whereas if x was 7 and y was 8 then it wouid vals to false The vale of a logical expression can be stored in a booi variable for Ister use Any merical expresslon can be used for the value of a condition wih O being imierpreted 25 false andl any non zero value as true This means hat the value returned by a relational expression could be wed in arithmetic Programmers often do this but it a practice not w be recommended I Teas 10 3 program tha is dificul to understand 611 Logical Expressions H is possible 1 specify more complex conditions than those which can be written using only the relational operators described above Since the value af a condition has 2 uel interpretation i could be operated on by the usual arithmetic operons this ix toto be recommended There are explicit loglal operators for combining the Topical ales rue and fakse The simplest logical operator is mot which is represented in C
86. guages and therefore ar portable between machines Compilers wast high level language instructions into machine code for ate Otten a single HLL instruction will be represented by several machine code Are ofen tailored to specifie kinds of problemn S FORTRAN sciatic calculation COBOL report generation handling business data C C general purpose problem solving languages Nee 1 45 High evel language examples Every language has its owm rules but there are distinct silts Below we show bow seen languages might eat out he numbers feom 5 10 10 Fortran a pova An for two low level language MCesono assembly language MC68000 executate 1 46 The Crt programming language We wil program using the C high evel language The C programming language was developed by Kernighan and Ritchie at Bell Labs in tie ariy 19704 1 it a powerful general purpose language developed 10 wark closely with the Unix operating astern Cr iss descendant of the C programming language ely it is C with a bunch at enara belis and whistles Cr isan object oriented language that in it incorporates many special fetes 1o cocapulate and manipulate user defined Kinds of data Most af the OO features of C W De discussed in he CSCI 161 Nec 1 Problem solving and software development 14 1Software Engineering Smal pograms es than 00 lines can be reliably developed by one person M
87. h up to nine characters since space is Deeded for the final ul character Strings can be seized at the neo declaration just as other variables are initialized For example woud store the wo tings as Tellows In the first case the aay would be allocated space for eight characters thai space for the seven characters of the siring and the mul character Inthe second case the tring i Set by the declaration to be twenty characters long but only sixteen of these characters are Sete the ile characters of the siring and the ul character Note that the length of ring does not nl the terminating nll character 10 7 4 String Output A string is output by sending it to an output stream for example woul peint The etw widik UO manipulator can be used before outputning a string the sring will hen be cup ight justified in the field wat T tbe Teld with ese than the length of the siring then the field with wil be expanded to fi the sting exactly If the suing iso De lef junified inthe eld then the sat1osiags manipilator wih the argument 10 7 2 String When the input stream cin is used space characters newline ete are used as separators and terminaors Ths when inpuing numeric data cin skips over any leading spaces and Terminates reading a value when it finds a whitespace character space tab newline ete 1 This same system is used forthe input of siringa hence a siring W be inp cannot start With leading spaces also i it has
88. he above algorithmie description is given below Tis Neic Since it was assumed in the specification that these would be Jess than 200 values the array sine is sta 200 In running the program less than 200 elements may be entered if elements where n lt 299 elements are emered then they will occupy the Tim places in the ray inata IC common to set an ara size to a Yale thi the maximam We think will occur in peatc though often ntl thi space will be used 10 52Example Program Test of Random Numbers The following program simulates the throwing of a dice by using a random number senerstoe 1o generate integers in the ange O10 The user asked 1o enter the number of al and the program outputs how many times each possible number occured An array has been used to hold the six coum This allows the program to increment the oreet count wing one siatement inside the loop raher than using 2 switch semen Tis Nec it six cases to choose between variables if separate variables had been used for each oun Also i is easy wo change the number of sides on the dice by changing a constant Because C arrays start at subscript O the count for an occuring on a throw is beld in the cath element of his cose array By changing the value of the constant Sse_ssaoe he program could be used to simulate a a121 985 sided die without any further change 106 Arrays as parameters of functions In passing
89. he actual parameter ul 1E i s required w return a value by a parameter then the address of the cul parameter used in the function call must be passed tothe function The fenton fan then use this address o acess the actual parameter in its own space in the Calling program and change if veqpired Thus what we are passing ls reference Io the parameter Hence callby referenee parameters To indicate that a parameter is called by reference an i placed after the type in the parameter list Any change that is made to that parameter i the function bady wil then erected in ite vale in the calling program For example consider the following function 10 evaluate the solution of a quadratic Tis Neic Note that the ots which are output parameters have been declared to be erence parameters while the coeficients are input parameters and hence are declared ob value Parameters The function prototype would have the following form This might be called in a program as follows Note haw the return value has been used to discriminate beween the situstion where the oot are real and are found im the wo output parametere and the case where the roots are Complet and no values far th root are returned 95 21Example Program Invoice Processing Deils of an invoice are available as follows Thus atypical set of input values for an invoice might be Indicating tha there are three items on the invoice the first item having
90. he variable The compiler will Neic orally truncate lat values othe integer Vale which is nearer to zero Rounding to he nearest integer is nor carried ou A similar problem arises with the division operator Consider the following rule The result of a division perso between two int operands is of type int It gives the result tranested wands zero if the resul is postive the Language does not define what sould happen if the result is negative This of couse means that it iS ery easy to lose accuracy if great care is not taken when wing division with Inge variables For example the statement Wil assign the value zero tothe integer variable Note that if the quotient af wo integers is assigned vo a float then the same loss of accuracy sill occurs Even if ia the above assignment was a variable of type troat 1 7 woul il be evaluated as an integer divided by an integer giving 2ero which would hen be converted 10 the equivalent 10t Value Le 010 before being assigned to the 103 variable The modulus operator between vo positive integer variables gives the remainder when the first is divided by the second Th 34 19 gives 4 ete onl However if eer operand is negative then there are ambiguities since it not well defined in C what should happen in this case For example 19 6 7 could be interpreted as 3 or Hence iiS best t0 avoid this situation All at C guarantees that Another problem associated with evaluatin
91. here already is am actual class definition and use i o i it has to be created List tor Apple alist List for Apple another it Tims will creste the actual class definition for a List and will rense it for another List CConsoguenlybsh are of the same type We summarize his in the following dition Definition Template Class M a class A is parameterized with a data type B A is called template class Once an object ofA i created an actual dara type replaces B Tiis allows the definition of an tu class based on the template specified for A amd dhe actual data type We ase able 10 Nec define template classes with more than one parameter For example directories ae Collections of objects where each object can be referenced by a key OF cause a directory should be able to store any type of object But there are also various possibilities for keys For instance they might be strings or pambers Consequently we Would define a template clans Directory that is based on two type parameters One for the Key and one far the sored objects 49 Static and Dynamic Binding In songly typed programming languages you typically have to declare variables prior to heit use This also implies the variables definition were the compiler seserves space for the variable For example in Paseal expressions ike Declares variable i to be af type integer Additionally it defines enough memory space to bol an integer value With the declaration we Bind he na
92. iable lives as long a5 Telerence r Reference er is defined as readonly constant reference This disables its use on the left side o assignments You may want to remove the comment in frant of the particular line to check out the resuling error message of your compiler 61 2 Functions C allows function ovetlaaling For example we can define two different functions imax one which rerums the maximuma of two integer and one which rerums the ratio of two seg The shove example program defines these wo functions which difer in their parameter lst hence hey define two diferem functions The fest pring call in function maint sues a eall wo the first version af marl because it tikes two integers as is argument Similarly the second prin eall leads to a cal of the second version af ma References can be used to provide a function with an alias af an actual function call argument This enables to change he value of the funetion cll argument ss known from other languages with cal by referenoe parameters g Neic 62 First Object oriented Extensions In this section we present how the object oriented concepts of section dare used in C 62 1 Classes and Objects Crt allows the declaration and definition of classes Instances of classes are called objects There we have developed a class Paint Ia C this would look like this This declares a class Poin and defines an object gpoint You can think o
93. ich instruction must be executed nex 1 33 Fetch Decode Execute cycle This eyele of events is being constantly repeated while the computer is tumed on When a program is running a copy of i stored in memory The CPU imes a register he program counter 1o keep wack of which program instruction ia going to be executed next Using the oomemnicanions bus and the value in the program counter the CPU asks memory to look up ete tne next instruction Long instructions may take several fetch stages The instruction i stored somewhere within he CPU possibly in an instruction register and the program counter is adjusted 1o point the next instruction The CPU decodes the instruction 10 determine what action needs t take place Finally the CPU caries out or exeues the instraetion The cycle is mow complete and con start again for the ext instruction 1 4 Computer software and languages 141Computerised problem solving There ane two key skills for developing sttware solutions to problems 1 Developing a plan or algorithm for solving the problem gt Requires good understanding of the problem om the user s perspective Requires an understanding of the general solution techniques and dala rage structures which are likely to be effective Requires a clear deseripdion af each phase of the solution in a logical and oreet fashion 2 Expressing the problem in a particular programming language gt Mast select a language support
94. ilar to traditional programming languages where you could have yo integers and j both of which equal to Please notice the use OF and Y in The Last sentence to name the evo integers We refer to the set of values at a particular tie as the state of the object Definition Object An objet is an instanceof a class I can be uniquely identified by ite name and defines a sate whic is represented by the values of ie abates at a Particular time The state of the object changes according to the methodi which are applied to it We referto this possible sequence of state changes as the behavior of the bj Definition Behavior The behavior of an object is defined by the set of methods which ean be applied on it We now have nwo main concepts of object orientation iateduced class and object Object oriented programming is therefore the iunplemmentation of abstract data types or 10 more simple words tbe writing of classes AL runtime instances ofthese chasses the jects achieve the goal of the programm by changing their sates Consequently you can think of your running program as a collection of objects The question arises of how these jects icra We therefore introduce the concept of a mesage in the next section 43 Message A runing program isa pool of objects where objects are crested destroyed and interacting This imeracting is based on mersages which are sent Troms one object 10 another asking the recipient to apply
95. ined The above aces examples seem 10 contradict this requirement Ix This realy wue Lets look again atthe two possibilities for representing imaginary umber Let s stiek othe seal part In the Tiest version equal e O In the second erion z equals cx In both eases x equals something Itis this somehing which tiles fren the actual data structure used Bu in both cases the performed operation ua has the sume meaning to declare to be equal othe eal part of the complex umber e both cases archive the same semanties If you thik of more complex operations the impact of decoupling data structures from operations becomes even clearer For example the addition of two complex numbers requires you to perform an tion for ach part Consequently you must access the value of cach purt whic i tien for each version By providing an operation add you can enenprulate these Skis from is actual use In an application cootext you simply add two complex umber regardless of how this funettonality is actual archived Once you have created an ADT far complex numbers says Compler you can use it in the same way like well Known data types such as integere Lats summarize thit The separation of data structures andl operations and the constraint to only access the data structure via a well defined interface allows you to choose data Sactres appropriate forthe application environment Neic 34 Generic Abstract Data Types ADT are u
96. ion implementation only segues the sendin of Three successive end of line characters to the output sireum cost None the introductory comment shat describes what the function does All functions should include this information as minimal comment Sine this function does not return a value it cannot be used in an expression adi called boy treating it msa statement as follows To Nec Even though there ate no parameters the empty parameter ist c mast be inserted When a function is called the C compiler must insert appropriate instructions into the bject code wo arange to pass the acu parameter values othe function code at 10 obtain any values turned by the function To do dis correetly the compiler must know the types of all parameters and the type af any eur value Thu before processing the call of a function it mt already know how the function is defined Defining any Tanerion that are wed in the main pogram before tbe main program can do ths Tor example the function xpires could be incorporated in a program as follows However this has disadvantages namely The main program tend w convey much more information of use in understanding the program than do individual functions So it is baer if the miin program comes fust However this means that the compiler tests The call of 2 function before i meets the definition of the function A using functions from a library of fantin then the main program is linked with the p
97. ion then th second flan wil mot be evauasd Tas dort eahsion enable any geal tapenian tbe efcienly eased Examples using logical operators Note that in the hist example an actual ruth value O fle was used as one of the operands of u this means that whatever the value of his logical expression eval to false Way In these examples brackets have beon ased to make the order of applicstion of operates clear However in the mains they are not strietly necessary if the precedence rules already considered for arithmetic operators are extended toned Telaional and logical operator The consequent extended Operator Precedence Table forts Be careful not to confuse the assignment operator with the logical equality operator Using this table with the following expression shows tbat dhe operators ane evaluated in the arder 7 lt t se a This is equivalent to bracketing the expression as follows or Neic Similarly the expressions write in bracketed form above could be written without bracken as Now that logical expressions or conditions in C have been covered it is ponsible to ove on and lok at the condtna conta stctre in C 612 Repetition Control Structures Jn previous section it was shown that algorithms can be described using a few concepts namely sequence conditional execution or Selection and repetition The idea of assignment was alio used This Secon considers repetition control s
98. irs al ver 1 4 6 The evolution of programming languages FORTRAN compiler first developed in 1957 Grace Hopper evenmaliy Rear Admiral in US navy key player in development af first compiler andthe COBOL programming language 1960 She is alg credited with cining dhe tenn bug val of subromine and more advanced programing sacs Neic Programming and software engineering techniques become key areas of research 1 1 7 Integrated circuits and operating systems 1 Integrated cizeuits allow thousands of logic devices to be placed in a single ap Again speed and reliability increase size and cost decease Use of software operating systema vastly enhances wsbilty and productivity of large systems o IBM starts he 360 series enables a new generation af massive software project and tremendous machine exis a improvement in data input and output wchniqus Computers now affondate for medium sized businesses 1 14 Microprocessors and PCs 197 first microprocessors and floppy disks available mosty built youre kite 1975 76 Steve Jobs and Steve Wozniak start up Apple computers Bil Gales starts witha BASIC compiler for the Alu founds Microsoft Numerous other small systems started Tandy Commodore ete 1981 IBM overwhelmingly dominates business computer market now emmers PC market 1982 Times man af the year is the computer 1984 the Mac introduced with window based graphics later copied by Micros
99. iructures They are farther expanded below Example One Using a whe loop The following algorithm illustrates several techniques The requirement is for a program which given a set of positive data values will output the minimum value the maximum Value and the average Value of he data values Before starting on the algorithmic description it must be decided how termination af the data is fo be signaled It would eating othe user if afier cach data ene a yes oe mo reply had to be given to a question asking whether there wat any more data Equally it might be difficult and error prone for he user to give a cust of the number of data elements before processing starts In this ease a better way is 10 make use of the fact that filth numbers are posiive the user then emersa negative suber when there are no ore numbers to process th n the program can emily recognise this etry as not being 2 dita entry and hence terminate the enuy of data This technique o placing a sentinel 10 Terminate an input ist commonplace It must also be decided what should happen when there is no input hat it the user enters a negative number nly Also it must be known wit type of numbers are entered are they mbole numbers or real numbers Hence he following improved requirement specication A user is to enter positive eal values from the keyboard when prompted by the program To signal end of input the user enters a negative number When data enty has terminated
100. ive that is gies information to the compiler but does not cause any exeeutabe code to be produced The actual program consists of the fet main which commence atthe line All programs must have a function matn None that the opening brace 1 marks the beginning of the body of the function wl the closing brace 1 indicates the end of the body af the function The word vosa indicates that nsin does not fet a value Running the program consists of obeying the statements in the Body of the function ws The body af the function a1 contains the actual code which is executed by the computer and is enclosed as mosd above in braces A semi colon terminates every statement which indructs the computer to do Something Symbols such aa natn 1 te ane ot incon odo seething and hence are not followed by a semi colon Sequences of characters enclosed in double quotes are Merl strings Thus instructions suchas send the quoted characters to the output stream cou The special ei saa Sen sent to an output ream will cause a newline to be taken on output Neic All variables that ane wei a progran must be declared and given a type In this ase al the variables are of type see Whole numbers Thus the statement Declares to the compiler that integer variables engi and viats ane going to be sod by the program The compiler reserves space in memory Tor these variables 9 Values can be given to variables by the assignment statemen
101. lation Steps 12 6 2 A Note abou Style Chapter 1 Principles of Programming Nee Principles of Programming 1 1 1 A quick history of computing 1 1 Karly devices and algorithms Computer software is based on algorithms formalized sequences of confcalculations which can be flowed to guarantee the correct solution af a problem Algorithms long pre dsted computers fo Fro the ancient Geek s we have Euclid algorithen for caleutiog estes common divisors o From the Chinese we have the abacus complete with algorithms for tio uluipeston division ete a From the 1600 the lide mule was used to perform muhipication division eau square rots logarithms ete 1 1 2 The first mechanical forts 1642 Blaise Pascal creates an adding machine that automatically carries from one column to The next TRON tbe Jacquard loons s invented the patera ofthe resulting fabric 3s programmed using loop of punched cand co Tae Holle uses puoched cats and a mechanical pumchisorting system ae used to carry out the US cous his company later to be a key player in ieemalation of IEM 1030s Konrad Zwe Alan Turing and others begin fundamental work an elecirormechanical systers and algorithms W ear out complex computations Both systems used for cryptographic and missile prototyper during the Wat 1 3 Te ierence engine in the mid 1800 Chases Babb age worked extensively on compen falelting devise the Diference engine for
102. ld the accumulated sum is initialised to zero Then a value fori entered so that x has value before being tested in the condition x gt 2 0 Note tha the value of 6 updated in the body of the wis lop before returning 1 st the Candian x gt 0 0 again The general form ofa weze statement is Tis Nec While the condition is true the statemen is epeately executed The statement may be a single Saement emniated by a semi colon or 2 compound ststement Now the following points Mt ast be possible wo evalue the condition on the fit emy to the hiie staoment Thus all variables ete used 1a the condition must have been given ales before the wise statement is executed In the above example the Variable vas given a value by entering value from the user At east one of the vatibles referenced in the condition must be changed in value n the ststement that constitutes the body ofthe loop Otherwise there would e no ay ol changing the wah value of the condition wich would mean tha tbe Loop ouid become a infinite loop onee it had been entered In the above example was given a new value inside the body of the vie statement by entering the Texa value ftom te user The condition i evaluated before the statement is executed Thus i the condition is initialiy false then the stemeet is never executed In the above example if the ter entered a negative number initially then no execution ofthe body of the loop would tke place
103. located 1 an sor vale by the computer system and compiler being used On PC most compilers allocate two bytes Tor each 1 Shick gives a range af 32768 to 432767 On workstations fou byles are usualy located giving a range of 2147483648 to 2147483647 I 1s important 1o ate ha integers are represented exactly in computer memory variates can represent any eal numeri value that is both whole numbers and uber that require digits after the decimal poiat The accuracy and the range of umber represented is dependent on th computer system Usually four byes are Allocated for 305 variables this gives an accuracy of about six significant 10 4108 Sigues and a range of about to It is important to mote that oat values are only represented approximately variables can only hold the values true or false These variables are known as Dole variables in honour of George Boole an ish mathematician who invented boolean algeten Nec tar arias represent a single character lene digit or a punctuation character They usually occupy one byte giving 256 different possible characters The bit puters for characters usually conform to the Americas Standard Code for Tnformation Interchange ASC Examples of values for such variables are A typical set af variable declarations that might appear at the beginning of a program Could be as Tellows Wich declarer integer variable 5 9 and count real variables sun and product a Stars
104. me to the type integer This binding is true within the scope in which is declared This enables the compiler to check at compilation time for type consistency For example the allowing assignment will teat in a ype mismatch error when yon ty to compie i vari integer We cal this particular type of binding tatie because it ie fixed at compile time Definition Statie Binding Hte type T of a variabile is explicitly associated with ts name N by declaration we say Mat Nataly bound to T Phe associanion process is called statie binding There exist programming languages which are not using explicitly typed variables For example some languages allow introducing variables once they are needed 1 No appearance afi 123 hein fas an integer 7 The type af iis known as soon as its vale is set In this case iis of type integer since we Tave assigned a whole number to it Thus bocause the content of isa whole umber the type ofi 1s imneger Definition Dynamic Binding M the type T of a variable with namme N is implicitly associated by its content we say that N ia dynamically bound to T The association process is called dynamic binding 7 Nec Both bindings differ in the time when the type is bound 10 the variable Consider the following example which is only possible with dynamic binding it someconditiono RUE then per che inh endif The type of afier if statement depends on the e
105. ment only allows selection of statement imple or compound when a condition holds If there are alternative statements some which need to be exerted hen the condition holds and some which are to be executed when the condition does ot hold This can be done with simple statements as follows This technique wil work so Jong athe statements wbich ae executed as a result of the first 2t statement do not ater the conditions under wbich the second seen will be executed Cr provides a direct means of expressing this selection The 12 9126 Sement specifies statements to be executed for both possible Jogical values of the oodles ian stiement The following example ofan i ctse statement writes out one message ifthe variable Lael poe and another message if ase is negative The general fom of the 12 0126 statement is t t eandiion semen Statement M the condition i tre then statement is executed otherwise statement is executed Both siea and satemen T may be single statements o compound sttmen Single tment ms be triad with a semi colon ay Neic 8 2 4 Examples of else statements The following i cisestitemen adds to a sums of positive numbers and increments a coun of positive numbers if itis positive Similarly fs negative it is added toa sum of Degative numbers anda count of negative numbers is incremented 8 22Example Program Wages Calculation An algorithm was developed to calculate wages dependi
106. mentation file Note the difference 10 the previous version where you just hide functions or procedures respectively Now you also hide information for an user defined daa type called list handle You use Ts erewe 10 obtain a handle 10 a new thus tangy is Every other procedure now contains the special parameter ix Which just identifies the list in question AN procedures now operate on this handle rather than 3 module global st Now you might say that you can creste list objets IS handle can uniquely identify each sich object and only those methode are applicable which are defined to operate on this handle 225 Modular Programming Problems The previous section shows that you already program with some object oriented concepts in mind However the example implies some problems wich we will outline 25 1 Explieit Creation and Destruction In the example every time you want to use a ist you explicitly have to declare a handie and perform a allo list erat to obtain a valid one Ate ihe use af the ist you mast xp eall fades withthe handle of the ist you want to be destroyed IF you Sant to use a lise within a procedure sy fot you use the following code trame Neic Let s compare the list with other data types for example an integer Integers are declared Wittin a pariculsr scope or example within amp procedure Once youve defined hem ou can we them Once you leave the scope or example the procedure where the intege
107. mented The rale is that a postincrement or postdecrement operator delivers the oid value of the variable before incrementing or decremeniing the Vanale A preinerement or peedecrement operator carmes out the anerementation first and then delivers the new vale For example has the Value S hen would set 2 to the original value of s ie and would then increment a 1 6 Whereas would increment n t0 6 and then set 1 10 6 For the moment this notation will only be used as a shorthand method of incrementing or comet a variable 103 Neic 17 Specialized Assignment Statements Another common simation that occurs i assignments such asthe follows in which a variable is increased by some amount and the result assigned back t0 the original variabile This Type of assignment canbe represented in C by This notation can be used with the arithmetic operators ands The general form al such compound assignment aperaiors i variable op expression wbich is interpreted as being equivalent to variable variable op expression the expression is sown in brackets to indicate that the expression is evaluated first before applying the operator op The following example ilustrate the use of compound assignment operators Except for the case of th compound modulus operator 1 the two operands may be any arithmetic type The compound modulus operator requires thst both operands are integer ype 78 Formatting of output es assum
108. n change the program to handle a different size of array Then if more records come 1o light it it easy to amend the program to cope with mare values by changing the valne of This works because the compiler knows the value of the constant n at compile time and can allocate an appropriate amount of space for the aray Ik would not work if an ordinary variable was wed for the size in th ueray declaration since st compile time the compiler would not kao a value for i 104 Accessing Array Elements Given the declaration above of a 1O0element array the compiler zeserves space for 100 consecutive lating point values and accesses these values using an inexact that Takes values from O 10 99 The ist element in an array in C always has the index O and if the array bas n elements the ast element wil bave the index 2 An array element is accessed by writing the identifier of the aray followed by the Subscript in square bracket Thus to set the 13th element of he aray above to 13 the following assignment is we m7 Nec Note that since the first element iat index 0 then the sth clement is at index 1 1 Hence in the above the Sth element has index 14 An array element can be used anywhere an identifier may be usedl Here are some examples assuming the following declarations A Value can be read into an array element directly using cin The element can be increased by S t using the shorthand form of the assigoment Ar
109. n checking that hes between 0 25 and 0 50 the test x lt 5 30 8 only fared out sf the test xe 2 25 has already failed hence x i greater than 0 28 This ows thar if x s less than 0 5 then x must be between 0 25 and O S Compare the above wth the following clumsy version using mare complex conditions Tis Neic 84The switch statement In the last Lesson it was shown how a choice could be made from more than wo possibilises by using nested oie stalements However a less unwieldy method in Some cases is 1o use a seiten statement For example the following sven statement iN set the variable arsa tote character A B or C depending on whether the variabile Tas the value 1 2 or 3 I has none af the Values 1 2 or 3 then a warning message is ouput The general fom of a sith statement is The selector may be an meger or character variable or an expesion that evaluates 10 an integer or a character The selector is evaluated and the value compared wit each of the ure labels The case Isbels must hae the some type as Ihe selector and they must all be iforent H a atch is found between the selector and one Of Te case label say labeli then the stemeot from the statement statement unt the next essa statement will be executed H the value of the selector cannot benched with any of the case labels then The statement associated with decouts is executed The deraut is optional but ir should only be lft out i is certai
110. n entension of C with a major addion of chass etc atun of Simula 67 Since the class wras a major addition to the original othe ginal C language Sioustrup called the language C with clases However ater in 198 he name changed to Ces The iden of Ctt come from the C increment operator thereby suggesting hat C is an augmented Version af C CH i a superset af C Most of what we already know about C applies to C also Therefore all C programs are also C progeams However there are a few minor differences that wl prevent a program 1o run under co complies The 3 most important features that C adds on to C are classes functions overloading amp perar overloading These fearen enable us to create abuact duta types inherit properes Irom existing data sypes support the polymorphism ths making Caz a truly thectriened language The objectoremed fanes in Cr allow programe 10 build Large programs with clarity extensibility amp eae of maintenance incorporating the apiri dt efliciency of C The addon of new furs has transformed rom a langage tat carey faites top down structured design to ome that provides batt bjc erened design 61 Mase Eatensons The following sections present extensions w already Inundieed concepts of C Section presents object oriented extensions C addi anew comment which i Induced by wo slashes U7 and wbich ats ual the end of line You can use both ones styles Tor example to comment out large blocks of e
111. n that the selector wil always take the alue of one of the Tie Neic case lsbels Note that the statement associated with a case abel can be a single statement fra sequence of statements without being enclosed in curly brackets Examples of switch statements The following statement writes out the day of the week depending on the value of an integer variable ay I assumes that day 1 i Sunday M it has already been ensued that asy takes a value between 1 and 7 then the aezauzt case may be mised out It is allowable 1o associate several ease labels with one Sttemeat For example if the above example iS amended w write out whether cay is 3 eekiday or is part of The weekend Remember that missing out a urea statement causes control to fall through to the next fase label this is hy fr each of the days 26 This is weekday will be output Nested if else statements can always replace switches but in some cases this may Be lume For example th weehdayweckend example above could be weinen a Nec However the fst example becomes very tedious there ae eight alternatives Consider the following 8 5The while statement The following pisce of C ilustrates a uns 1e statement Ht takes a value entered by the ser and a long a the wer enters positive values it accumulates their sum When the ser eners a negative value the execution of the whe statement is terminated The variable sum which sto o
112. neral form of the a n ze statement is sae 4 condition 1 note the bracket In the do ehste statement the body of the loop s executed before th first test of the condition The loop is terminated when the condition becomes false As noted above the loop statement ie aways executed at least onee unlike the wie statement where the bady of the lop is not executed arall if the condition s initially false The statement may oa single statement or compound statement The effect of a dove semen can always be simulated by ante statement so itis not ely necessary However in some Situations itean be more convenent than a w512 satement 6 1Esample Program Sum of Arithmetic Progression The following Koop produces the sum 2 3 0 Where a value fo n is entered by the M the user entered a valie of O for n then the value of 1 would be retuned as the value of sun This i obviously incorrect and a noted sbove is because th loop sialement of eunte loop is always executed at least once In this case if the entered value of Zero then the oop statement should not be entered at ali Thus if there i any possibiliy That some valid data may require that loop be executed zero Umes then a ste salement should be used eather dham a do wti 2e statement 8 62Example Program Valid Input Checking The a v 1e statement is useful for checking that input fromm a user lies in a valid range and repeatediy requesting input umit i is within range Thi sted in
113. ng confit 3s introdced ifa class D rail inherits from super chasses B and C which themselves are derived from one super class A This leads an inheritance raph ms showa a Figure 63 gue 3 A name lien by aT class of sapar lasset wed wits maple The question arises wut properties class D actully inherits from is super classes B and C Some existing programming languages solve this special inheritance graph by deriving Dwin The properties ofA plis The properties of and C without de properties they have inherited from A za Nec Consequently D cannot ineeduce naming conflicts with names of class A However if 8 and C add progenies with te same ame D runs ino a naming conflict Another possible solution i that D inherits from Both inheritance pats In this solution D owns Ewo copies of the properties of A B and one by C inherit one Although multiple inheritances is a powerful object oriented mechanism the problems inwoduced with naming comets have lesd several authors doom AS the result of Multiple inheritances can always be achieved by wig sirnple inheritunce some abject oriented Languages even dont allow is use However carefully used under some ondions muluple inheritance provides an efficient and elegant way of fooling Things 47 Abstract Classes With inheritance we are able to force a subelass to offer the same properties like their super clases Consequently objects of a subclass behave lke object of their super
114. ng on hous worked and on Werer any overtime had been worked This can now De writen in C The program is ised below m Neic Note tha this program cotsns the minimal amount of comment that a program shoul contain Comments have been used to indicate who wrote the program when it was written ad what it does discribe the main stepa ofthe computation indicate wha the program variables represent Also note how constants have been used for the number of houes at which the overtime Weighing factor applies and the weighting factor ill Heee if subsequent negotiations Change these quantites the program is easily changed 8 23Example Progra Pythagorean Triples mon Write a progam to input owo integer values mand where apd to ouput the m n mnt conesponding Pythagorean riple 2roreand Tis now extended So that the values of Mand Menteed by the user ae validated 10 ensure that Ms reat than 1A A suitable alginic description This algorithmic description is now easily converted into the following C program Tm Nec Note that the value of n and n entered by the user are printed as part of the output This ik good practice Programs should oot only display resulis but should give some indication of the data that produced the resus In this case he input data set was produced in full since it was small In situations where the input data set was age it Tight not be realistic to reproduc
115. ngs are quite diferent a show in able 9 1 The leftmost column ists possible aces rights for elements of classes It also includes a Third type erotectoa Ths type sued for elements which should be directly usable in Subclasses bur which should not be accessible Trom the outside Thus oae could say lements of this type are between pr tats and pb elements in that they can be used Within the clas hire rooted by the conesponding elass The second and third Column shows the resulting access right of he elements of a superclass when the sabelas is privately and publically derived respectively ype of Taheritance private peblic Tints priate pate protected private T protects pul pasate pili 12 1 2 Construction When we create an instance of clas Pont2D its constructor x called Since Poin is derived rom Pointe constructor of elass Point is also called However hs constructor s called Before the body of The constructor of class Pointa i executed Ta general plor tothe execution of the particular constructor body constructors of every superclass are le initialize their part of the crested object Tm Nec When we create an object with the second constctor of Point3D is invoked Prior to the execution of the constructor body the constructor Painf 36 invoked w initialize the point part of object paint Fortunately we have defined a constructor which takes no arguments This constru
116. o for the Windows system the PC wars are on 1 1 9 The Internet computers and communication 1969 Arpanet commissioned by US DoD 1970 connected wo ALOHA net 15 sites by 1971 international links added in 1973 1074 TCP transmission control program and FTP file transfer protocol inuodiced 1976 Queen Elizabeth es ot email far the first time 1979 USENET news groups crested Early 1980s se widespread connections to networks by universities 100 hosts in 1984 T 1o00 hosts in 1987 7 tonond hoss ia 1980 oon hosts ia 1992 Gopher released 1991 WWW released 1992 Mosaie takes web by Storm 1993 incredible trafie growth on web 1 1 10 A the search for thinking machines Nec 1940s Alan Taring suggests the Turing Test of machine intelligence 1950 Minsky and McCarthy set up the Artificial Ielligence Department Mir IOTOSELIZA diicuty of Al becoming obvious 1980 to present Neural networks sl ining systems Export systems seeking answers in complex search spaces Natal language processing fundamental hardness of natural languapes July 97 Deep Blue IBM chess machine bests Kasparov in repeated manches 1 2 Some Remarks about Programming Programming is a cone activity in the process of performing tasks ar solving probleme withthe ai af a computer An idealized picture i Problem or task specication COMPUTER solution or completed task Unfortunately things are mot yet that simple
117. o implement thea operation We could read the part i a ad the vale oft the valie oth the ADT level this esl in Precondition Let iadd T Postconditions i 2 with n1 n2 particular Teens E Nec The postconditions ensure tht andj do not change their values Please recall the specication of aids I says that a mew Integer i created the Value of which is the sum Consequently we must provide a mechanisms to access this new instance We do this with the set operation applied on instance k Precondition Let k n where n is any Integer eet ad K Poscondtons k As you can see some programming languages choose a representation which almost quale the mathematical formulation used in the pre and poscondiions This makes it Sometimes dificult not mix up both levels Chapter 4 Basic Concepts of Object Oriented Programming Nec Basic Concepts of Object Oriented Programming 4 The previous sections ead introduce some object oriented concepts However they were applied in a procedural environment or in a verbal anner In this Selina We Investigate these concept in more deil and pive them nae at used in existing object need programming Langues 41 Class A elas is an actual presentation of an ADT M therefore provides implementation deils far the data structure wed and operations We play with the ADT Jaeger and design out own clas for it in the example shove as well as in examples
118. of implementation files Consequently they are included ia each implementation file which uset the interface of the particular implementation file As mentioned in previous sections this inclusion it achieved by 2 copy of the content of the hender fle at each preprocessor fn statement leading 10 ainge nw C4 fle To avoid the inclusion of multiple copies caused by mutual dependencies we use conditional coding The prpeoesse also defines conditional statements 1o check for Various aspects of is processing For example we can check if a macro i aleady defined The lines between pindar and senai are only included if macso is mot already defined We can use Ihis mechanism to prevent lip copies To Avez is a unique name for each header file You might want 1o follow the Tonvention of using the namme ofthe file prefixed wih two underbart The firsttime the le is included _ semeaz is mot defined thus every line is included and proceed The first line just defines a macro called _ erazanER 5 I accidentally the fle should be included a second time wl processing the same input fle vuzaoen 6 defined thus everything leading up to the Fons skipped 80
119. on and as data sa very powerful feature allows programs to generate other programs and have tem executed 1 3 Hardware Software Interaction 1 31 Source Code compiling and execution Once a programmer has decided how to solve a problem they need to wet the solution out in a valid programming language eig C29 Sauce code the program created in a human readable formats e when we Wate code usiag C The computer cannot dicey ran this human readable format s0 when You got run the program a compiler Istch a pec or g mast irst be used to translate the source cde into executable code The compiler translates the source code Inia another format one hat the computer can ran or exeewe Source code is generally portable can be used on different machines Whereas executables rely on machine specie information 132 Running a program Eecuble programs as well at source code are stored on secondary storage usually disk deives To exeete a program it must be copied nto main memory and space set side for variables subroutine calls ete Every individual instruction and every piece of daa exists at some unique location or address in memory To execute a program the computer keeps track ofthe memory address of Ihe next aston it mst execute Execution then consists of repeatedly Neic Fetching the next instruction to be executed Decoding the instruction deciding what must be done Executing the instruction and deciding wh
120. on prototype for the parameterized version of skip would be 9 43 Functions that return values One o th mast wel forms of function is one that returns a value that is a function of its parameters In this case the type given to the funetion is hat of the value 1 be eumed Thus consider dhe function previously considered which given the co ordinates tpl owl enuen ks tance Trom the origin m2 Nec The function prototype for this function is This function introduces several new features Not the following The funtion has been given the type isat because it is going to reruma 103 vale The porumeter list now has two parameters namely x and y Each parameter i declared by giving its type and a comma separates name and successive parumeler declarations A local variable aise has been declared to temporarily hold the calculated distance Because this function returns a value it includes a return statement wbich returns the value In a siatement seca valne the value may be a constant a Variable or an expresion Hence the use of the local variable a1 was ot seal since the ot uen statement could have been weinen When the fenton is called the formal parameters x amd y are replaced by acta parameters of ype 203 and in the same order Le the x coordinate fist Since the fanetion returns a value it can only be used in an expression Hence the following examples of the use of the above function in a p
121. only initialize the first five 10 5 1Example Program Printing Outliers in Data The requirement specification for a program is Tis Neic A set of positive data values 200 is availible It is required to find the average value of these Values and to count the number of values that are more than 10 above the average value Sine the data values are all positive a negative value can be used as a sentinel to signal he end of data entry Obviously this sa problem in which an array must be used since The values must first De entered to find the average and then each value must be compared th this average Hence the use af an array To store the entered values for ater re use An initiat algorithmic description is Thus canbe expanded tothe complete algorithmic description in the above the variatie coqeio tthe member greater than 10 above the average value Iis easy to argu that afier exiting the us 2 loop coun is set to the number of positive numbers entered Before entering the loop cous i set to zero and the first umber is entered that is count is one less than The mumber of numbers entered Each Time round the loop acter number is entered and count i ineremenied hence court Temains one less Ihan The number of numbers entered But the namber of numbers entered it one greater than the namber of positive numbers so ount i therefore equal 10 the umber of positive numbers A nsin 0 program written froma t
122. ost oftware is developed in much larger environments Wih teams of programmers or even colleetions af teams Managing large projets involves many more organizational difficulties than the smal single person projets Software engineering isthe study of processes by which lage projects can be developed We wil uy 10 help you develop skills which will make you comfortable in both 1 5 2 Software fe yee The sages a typical piece of software goes through from inti conception 10 hlescenee 1 Analysis specifying exactly what the problem is and what are the requirements for an acceptable solution Design developing a detailed solution to the problem Coding unin the design into a working program Testing verifieation ensuring the software is correct Maintenance fixing enhancing adapting the software Obsolescence abandoning a program which sno longer effectively maintainable 1 5 3 Problem solving process We want to build good problem solving skills for software development This means skills which can sucesflly be used 1o ace larger and more complex problems The desinldocumentaton techniques may seem like overkill for smal problems THE PRACTICE IS IMPORTANT AND VASTLY WORTHWHILE LATER ON Planning organization and documentation prevent a preat deal of grief in program development and maintenance 1 54 Program development Maintenance af programs will not be heavily emphasized in this course hough it will be ey impo
123. pence by 100 Also how the v operator hat been wed t0 find the remainder when pence ts divided by 100 to produce the number af peace left Nec 716 Increment and Decrement Operators Ther are some operations that occur so frequently in writing assignment statements that Cr has shorthand methods for writing them One common situation is tht of incrementing or deerementing an integer variable For example C has an Inerement operator and a decrement operator Tas 15 can be used instead ofa n oy can be used instead fa gt 0 The and operate here have been written after the varisble they apply to in which case they are cae the postinerement and postdeerement operator Tere are aso denial preinerement and predecrement operators which are written before the variable te bich they apply Thus vas can be used instead of n ne can be nsed instead ofn 2 Both the pre and post versions of these operators appear 1o be the sarne from the above and in fact it does mot maner whether nes or e is used IF all thut is required i 0 increment the variable n However Both versions of ihe increment and decrement operators have a side effect which means that they are not equivalent in all cases These operators as well as incrementing or decrementing the variabile also reram vale Thus What value does take Should it tske the old value of n before it is incremented or the mew value afer iL i incre
124. playlacele 7 Should invoke stele pit Gsplayaretangle Should invoke rectangle print The actual method should be defined by the content of the object o of function dsp Sine this somewhat complicated ee is a more abstract example class Base nrus methods ital oa a aus Derived nbesit trom Base nibus methods ital oo a i demotiase o 000 ba Base abuse Derived derived dematsbase demo aderived In this example we define two classes Base and Derived Each class defines two methods oo and bart The first method i defined as virtual This means that if his method i invoked is definition should be evaluated by The coment of the object We then define a fanetion dem which tikes a Base objet at its argument Consequently we can we this fanetion with objets of clas Derived as the iva relation hold We call tnis unction With a Base object and a Derivedobject respectively Suppose that fot and at are defined to just print out their name and the elass in which they are defined Then the ouput is as follow on of Base ale bart af Base called foo of Besse called Neic bart of Base called Why is this s0 Lers see what happens The ist eall ro demol uses a Base object Thus the functions argument ile with an objet of class Base When itis Uime 1o invoke method foo is actual functionality is chosen based on the curent content of the Corresponding object o This time
125. ployes data only with associated operations This allows you to ensure That data elements are always in a proper sate Por example you are able to check if 3 Provided dates valid Tosum up abstraction is te structuring of a nebulous problem into well defined entities by defining their data and operations Consequently these entities combine data and operations They are mot decoupled from each other 3 2 Properties of Abstract Data Types The example of the previous section shows that with abstraction you creste a well defined entity which can be properly handled These entities define the data acre of set of ems For example ach administered employee has a name date of Bith ad Social number The data structure can only be accessed with defined operations This set of operations is called interface and is exported by the entity An entity with dhe properties just desenibed called an astraer dara ype ADT Figure 32 shows an ADT which consists of an asta data structure and operations Only the operations are Viewable from the ouside and define the interface w Nec aera ype Once a new employee is eres the data structure i led with actual values You now have an instance of an abstract employee You can create as many instances of an abract employee as needed 1o describe every real enplayed person haracteristies ofan ADT Definition Abstract Data Type An abstract datatype ADT is characterized
126. provided arguments ab well a6 preconditions and Postcondisons are given As an example the description ofthe ADT Integer is presented Let k be an integer expression ADT Integer is Data A sequence af digits optionally prefixed by a plus or minus sign We refer to this Signed whole number 2 Operations Constructor Crentes a ew integer Add Ceeates a mew integer which the sum of Nand E Consequently the pastconditions of his operation is mum Nek E Neic seb Similar 10 add this operation crestes new integer of the difference of both integer values Therefore the ponicondnions for this operation is sum N k set Set M to k The pstcondiions for his operation is V k End The description above is specification for the ADT Integer Please notice that we use words Tor names of operations suchas add We could we the more intuitive 2 sgn instead but this may ead to some confusion You must disingulsh the operation from th mathematical use of in the postconins The name of the operation just syntax wheres the semanties i described by the sociated pre and postcondiions However it is always a good Mea to combine both to make mending of ADT specifications easier Real programming languages ate fee to choose an arbitrary Implementation fot an ADT Fot example they might implement the operation add with the infix operator 4 leading to a mone itive lok for addition of iniegers 16 Abstract
127. r was defined the Inter is lost It is automatically created and destroyed Some compilers even iniialize newly crested integers to a specifie value typically O ero Where is the difference to list objects The tine of a list is also defined by its scope henee it must be created one the scope is entered and destroyed onee iti left On crestian ime ast should be initialized to be empty Therefore we would like to be able To define a list similar wo the definition of an intsger A code Trame Tor this would loak tke tis The advantage is that now the compiler takes cure of calling iialiation and lemitation procedues as appropriate Por example this ensures that he sti corel ete returingesourees to the program 25 2 Decoupled Data and Operations Decoupling of data and operations eads usually to a structure based on the operations rather than the data Modules group common operations such as those lat operations together You then we these operations by providing explicitly the dato tem on which they should operate The resaling module structure i therefore oriented fon the operations rather than the actual data One could say that the defined operations specify the dats tobe used In object orientstion structure i organized by the daia You choose the data representations which best fit your requirements Consequently the daia Father than operations suucture yout program Thus i is exactly the other way around Data
128. ray elements can form part of the condition for an ie statement or indeed for any ter logical expression or statements are the usual means of accessing every element in an array Hese the fist i elements of he array ansa tomp are given values from the input sirem os The following code finds the average temperature reconded in the first ten elements of he amy Notice that it i good practice to use named constants rather than literal numbers such an Oct the program is changed to take The average of the fist 20 enues then al too easy Mo forget ta change 104020 Ma const is used consistemiy ten changing is value will be ali that is necessary For example the following example finds the average of dhe last x enries in the array x ould either be a variable or a declared constant Observe that a change in the value of x wl sail calculate the correct average provided x Tis Note C does not check that the subscript that is wed 1o reference an array element cly ies in The subscript range af the asray Thus C Will allow the assignment ofa alue 10 sorus sen however he effect of this assignment is unpredictable For example it could ea to the program attempting to assign a value to a memory element that outside the programis allocated memory space This would lead to the program being terminated by the operating system Alternatively it might actually acces 2 memory location that is within the allo
129. rce every derived elass fram which objects should be creado define a method printf These method declarations are alo called pure etka Pre methods must also be declared virtua because we only want to use objects fram derived classes Chases which define pure methods are called abstract lasses 124 Operator Overloading H we recall the abstract data type for complex numbers Complex we could create a Ce class as follows Trs Nec We would then be able to use complex numbers and yall with them Here we assign e the sum of a and b Although absolutely cornet it does not provide a convenient way of expression What we would rather like to use is the well known 10 Express addition of wo complex numbers Fortunately C allows us to overload aoe of ts operators for newly created types For example we could define 4 operator for our class Complex Inti ease we have made operator a member of class Complex An expression ofthe fom swans into a method all Thus the binary operator only needs one argument The fist argument is implicitly provided by the invoking object in this case a However an operator call can also be interpreted as a usual function call as in In this case the overloaded operator is mot a member of a class It is rather defined ouside a normal overloaded funcvon For example we could define operator in his T6 Neic In this case we must define access methods for the re
130. recompiled object code ofthe functions Thus while compiling the main program on its own the compiler ha no knowledge af the function definitions The way round both the problems above is to use Function prototypes A function prototype supplies information abou the etum type of a fanetion and the ype of it parameters This function prototype then placed before the main program that wes the fanetion The full function definition is then placed aller te main program or may be contained in a separate fe that is compiled separarely and linked w the main program Ister The function prototype is merely a copy of the function heading Thus the function retype for the functions ipchewe i Tao Neic Which would be included in the program file as follows In fact when using functions from the steam libraries and the mathematical libraries proorypes are required for tbese functions This is handled by including the files Tat teann and nati which among other things contain the function prototypes 9 42 Functions with parameters and no return value The function of the previous section is not very useful what if four lines were to be skipped or two lines Ht would be much more useful if it was possible to telt the function how many lines to skip That isthe function should hive an input parameter which indicates how many lines should be skipped The function sxtpeneoe 1 ia now changed to the function se which has a parame
131. responding abject sends a message to the screen object This message requests the Sereen abject to display the associated key value 45 Relationship 45 1 A Kind Of relationship Consider you have to write a drawing program This program would allow drawing of various abjecte such as points circles rectangles tangles and many more For each bject you provide a elass definition For example Qe point class just defines a point by ies coondinstes You continue defining classes of your drawing program with a class to describe cicles A circle defines a centet point and a radius w Neic Comparing both cas definitions we can observe the following oth classes have two data elements x and y In the class Point these elements describe the position ofthe point in the case of class Cirele they describe the Circle s cemer Tims x smd y have the same meaning ia boih classes They Seseribe the position of their associated object by defining a poiat Both classes offer the same set of methods to get and set the vale of the wo data elements xand y hiss Circle adds a new daa element radius and comesponding access methods Knowing the properties of class Point we can describe a ciscle as a point phus a radius and methods to acess Thus a cicle is akind of point However a circle is Somewhat mare specializnd We ilustrate this graphically as shown ia Figure 5 1 Ta Poet In this and the following figures class
132. responding poiner type The srp pointer can be setto other aston Jus destination may vary In conas to that arrays are fie pointers They point to a predefined area of memory which is specified in bracken You can view str to be a constant pointer pointing to an area of 6 characters We are mot allowed wo use i like tis Because this would mean to change the pointer 1o W We must copy the string into the provided memory area We therefore use a function called steep Which is par ofthe nd C library Note however that we can we sr in any case where a pointer to a character is expected because ised pointer 5 1 6 A First Program Here we insoduce the fist program which is so oflen used a program which prints Hello world to your screen Chapter 6 From C To C Nee From C To C 6 60 History of Cre his section presents extensions to the C language which were introduced by C It also deals with object oriented concops and thei realization C i a objeet arenied Programming Language Illy named e with classes C was developed by Bjarne Suoustyp at A T amp T Bell Laboratories in Murray Hil New Jersey USA in the early fini Swousarup an admirer of Simula 67 and a stong supporter of C waned 10 ombine the best of boh languages amp crete a more powerful Language that could support sjact oriented programming features and sl stain the power amp elegance af C The teat was Co Therefore Crs isa
133. returns the distance of the point x y from the origin In Ihe function local variable aise i wed 10 Temporarily hold the caleulated alu inside the function The general form of a function definition in C is as follows Acie type function name parameterdist y Incal definitions funenton implementation M the funtion returns a value then the type of that value must be specified in funetion ype Far the moment this could be soe 1052 or enar I the function oes not return a Value then the fanction type mast be vos The fancton name follows th same rules Gf composition as identifies The parameter ists the formal parameters of the function together with their types The loaldefinions ave definitions of variables that are used in the function implementation These variables have no meaning outside the faction The function implementation consists of C eecusble statements that implement the effect of the function 9 4 1Functions with no parameters Functions with mo parameters are of limited use Usually they will not return a value but arny out some operation For example consider he following fanton which skips three Tines on ouput Note that the fantom ype has been given as vosa this tells the compiler that this fanetion does not return any value Because the function does not ake any parameters the parameters empty his 3s indicated by the vo parameter ist No local variabler are required by this funcion andthe finer
134. riable foe the accumulated sun this must start at zero 2 a variable forthe number of values again this sas at zero 3 variables forthe suved maximam and minimam atthe first execution of procesa value the only previous value is the firs value hence the initializition Eo set the saved maximum and the saved minimum 1o his value Hence the beginning of the program can be expanded to T Nec M mo datas entered then this can be recognized by the fact that cout will be zero afler execution of the wns te statement Finding the average merely requires dividing the sum by the count of values and tpt iy obvious Thus the final version i Note that if no data is entered then the terminating negative value will be assigned 10 nim and mazimum This does not mater because in This case no use is made of These variables Example Two Using a white A set of marks are available for a class of students Foe esch stat the following details ame available poreentage exaninat ton mark for subject 1 2 percentage coursevors mark Tor subject 2 Aar SEAE ware cpr SAAE A program it required which will read in the marks at above for each student and will output for each student in one line the above information wether with a final mark for ach subject The final mark in each subject is VO af the examination mark plus 30 of The coursework mark The average final mask far each subject soul also be output End o input sto be signaled
135. rogram in wich itis declared A function may have several return statements This is astra ia the following fanetion which implements Ihe algorithm for evaluating the square root previously considered Tm Neic M the function has type wosa then it must wor return a value Ifa voi function does eum a value then most compilers will issue some form of warning message that a retum alte ino expected 9 43 1Example function sum of squares of integers The following function seturns the sum of the squares of the fist n integers when it is called with parameter A typical we of sung 9 4 3 2E sample Function Rasing to the power This function returns the value of is first parameter raised to the power af its second meer The second parameter is an integer but may be O or negate Tiu Neic A typical use af the poser function is shown below 9 5 Calbby vale parameters Suppose the function ponar above is now amended to include the statement just before the final closing and the following statements are executed What would be printed out for the value of In fact instead af the value 5 that you might expect p would suli have the value 4 This i because th parameter has been passed by value This means hat When the function i called copy of the value of the etul parameter used in the eall is passed actos 10 the memory space of the function Anyhing that happens inside the function to
136. rtant in later courses so our main development concerns will be 1 Analyzing the problem we e given 2 Developing a volution technique algorithm 3 Documenting the progranechnigue 4 Translating implementing the technique into code Nec 5 Compiling and running the program Testing the resus with appropriate data Stapa 3 through 6 will be repeated until the program handles all he test cases corneetly 1 55 Incremental development When implementing compiling and testing DO THIS AND SAVE YOURSELF HIDEOUS NIGHTMARES 1 irs get a skeleton outline solution for the problem 2 Getit implemented running and tested 3 Flesh out ome more part of the program A Getit implemented running and tested S Repeat stept 3 and dul the whole thing is done M you design and cose the whole thing in one fell swoop hen uy to complldebu it you na find the problems overwhelming 1 56 Design and alysis Analysis includes Determining the input data for th program Determining the output that must be produced Mdemifying any iaformation needed get Trom the inputs to be output Design consists primarily of working out an algorithm That i a step by sep prvosdure for solving the problem based on the analysis 1517 Top down design Many problems are too lage to immediately grasp and solve all the details top down design tries to address this sue Take a problem divide it into smaller logical sub problems an
137. s This is because ia all these programs it has never been necessary to keep a note af each mamber individually for lar processing For example in summing the numbers in a list only one variable was used 1o hold the current tered number which was added io the acaulaod sum and was then ever by The nox number entered H that value were required again Ister in the program There would be no way of accessing it because the value has now been overwrinien by the later M oniy a few values were involved a different identifier could be declared for each variable but now a loop could not be used to enter the values Using 3 loop and assuming Tat afier a value has been entered and used no further use wili be made of it allows the following code to be writen This code enters six numbers and cuts thair sum This of couse is ensily extended to n values where can be as large at required However ia was required to access the values later the above would not be suitable It would be possible to do it as follows by sening up six individual variables and then handling euch value individually as follows Which is obviously a very tedious way to program To extend this solution so that it Would work with more than six Values then moe declarations would have to be added fu assignment statements added and the program recompiled If there were 10000 Values imagine the tedium of typing the program and making up variable names and remembering which i which
138. s own a driver program would have to be writen A driver program is a simple program tht allows the programmer to emer values for the parameters ofthe Tuscon 1o be ested and outputs the resus A suitable driver program totes te above function could be Tio Nec When testing functions uy to use one example of each af the cases that can occur For example using the above driver program 1o show that ca coos works fo mes 1 1033 ota complete test since it does not generate any carry Irons the pence 10 the pounds An additional test on say 6 times 173 checks that tbe carry works Choosing a se o lest aa to adequately validate a function requires much tought Nic Chapter 10 Arrays Arrays 10 10 1 What isan Array An amay in a se of variables represented by a single name The individual variables ase oh ae dete by index number The folowing example declares an The ist element in the aray has an index namber of 2er Therefore the above aray has Neic Variables ia a program have values associated with them During program execution these values afe accessed by using the identifier associated with the variable in expressions ete In nome of the programs ween so far have very many variables been sed to represent the values that were required Ths even though programs have been erent could handle large sts of numbers it has not been necessary To use a separate eter for each mumnber in the L
139. se objects of class Dravablestring like both points and strings Because a dravablestring a point we can move them around Since itis a string we can append other text 1o them Now it s time for te definition of multiple inheritance Definition Multiple Inheritance 1f class A inherits from more thon one class ie A inherits from BL B2 Bre we speak of multiple inheritance This may introduce zg Nec naming conflicts in A if at east twos of is super classes define properties with the same The above definition introduces naming conflicts which occur if more than one superclass of a subelass use the sme name for either stiributes or methods For an example let s assume hat elast String defines a method rer which sens the string 103 Sequence of 3 characters The question arises what should be inherited by DrawablSiring These conflicts can be solved in at east two ways The order in which the super classes are provided define which property will be accessible by the conflict causing name Others wil be hidden The sabelas mast resolve the conflict by providing a property with he name and boy defining how to use tne ones from ite super classes The first solution st very convenient as introduces implicit consequences depending an the order in wbich classes inherit rom each other For the second case subclasses must explicit redefine properties which are involved in a naming confici A special ype of nami
140. sed to define a new type from which instances can be crested As shown in The lst example sometimes tnet instances should operaie on other dala types as well For instance one ean thinkt of liste of apples cars or even lists The semantically definition of a Iia is always he same Only the type ofthe data elements change according to what type the lis should operate on This additional information could be Specified by a generic parameter which Is specified at instance cteaton time Ths an lave of a generic ADT is actually an instance of a particular varant ofthe ADT A ist af apples can therefore be declared as follows The angle brackets now enclose the duta type for which a variant af the generic ADT List should be crested listOfApples offers the same interface as any orher ist ut operates oa instances of type Apple 45 Notation As ADTs provide an abstract view 1o describe properties of sets of entities their use is independent from a particular programming language Each ADT description consists of tvo pares Data This part describes the structure af the data used in the ADT in an informal Operations This purt describes valid operations for this ADT hence it desribes its interface We use the special operation constructor to describe the actions Which are to be performed once an entity of this ADT is crested and destructor 1o describe the actions which are to be performed once an entity i destroyed For each operation the
141. specifas valid operations Now madiales group data representatioas together 25 3 Missing Type Safety In our list example we have to use the special type ANY to allow he list w carry any data we like This ingles hat the compiler cannot guarantee Tor type safey Consider the Following example which the compiler cannot check Tor correctness Nec 11 isin your responsibilty to ensure that your list is used consistenily A possible solution is to additionally add information about the type to each list element However tis implies mose overheads and does not prevent you from knowing what you are doing What we would lke wo have is a mechanism which allows ust specify on which daia ype the Ist should be defined The overall function of the list is always the same Sheer we store apples numbers cars or even lits Therefore it would be ceo ciare a new list wit something lka The corresponding list routines should then automatically retum the correct dita types The compiler should be able to check for ype consistency 25 4 Strategies and Representation The list example implies operation to traverse through the list Typically a curso is used for thut purpose atch pins to the current element This implies a inversing reg which defines the onder in which the elements of te data structure are to be vised Fora timple data structure like the singly linked list one can think of only one Iraversing Sralegy Staring with th
142. sponsible w initialize and desaroy sel correctly Consequently there i no longer the need 1o explicitly call 3 resrion or terminon procedure You might ask So wha a r this just a more faney modular programming teclnigue You were night if this would be all about object oenation Fortunately i not Beginning vith the next chapters additional features of abject orientation are introdueed which make object oriented programing wo a new programing technique Chapter 3 Abstract Data Types Nee Abstract Data Types 3 Within this section we introduce abstract data types as a basie concept for object weston und we explose concept used athe Ist example of the st section in mane tai 31 Handling Problems The fist thing with whch one is confronted when weking programs is the problem Typically you ane confronted with real life problems and You want to make lfe easier by praviding a program forthe problem However eae problem are nebulous and efit thing you have to do sto uy 1o understand the problem to separate necessary from unnecessary das You uy to obtain your own abstract View or medel of the problem This process of modeling called abstraction and laste in Figure 31 z Sop Problem Abstraction Le The model defines an abstract view to the problems This implies hat the model focuses anly om problem related stu and that you Uy to define properties ofthe problem These Properes include
143. ssion Function It append takes one argument data of sbieaty type This is neessary since you wish io use your list in severa diferent environments benee the type of the data elements to he soned in the liat is not known beforehand Consequently you have 1o use a special ype ANY which allows assigning data of any type to it The third procedure ised neds to be called when the program terminates 1o ensble the module wo cleanup it imernally used variables For example you might Want wo release allocated memory With the neat two procedures fst getFirst and limt getNen a simple mechaniem 1o averse trough the ist is offered Traversing can be done using the following loop Now you have a list module which allows you to use a list with any type of data elements But wst if you ned more than one st in one of your programs Nec 2 42 Handling Multiple Lists You decide wo redesign you lst module to be able to manage more than one list You Kherefore create a new interface description which now includes a definition fra list handie This handie i used in every provided procedure to uniquely identify the Uist in question Your interface definition file of your new lst module looks like this You ute DECLARE TYPE o introduce new type list _handle t which represents your Hst handle We do not speci how this handie i actually represented or even implemented You aso hide the implementation details of ths ype in your Imple
144. t TRUE For example the standard function sir kes two strings a argument and ret 1 ifthe ist i lower than the second O Af tbey are equal and 1 the fist reser than the second ome To compare if vwo siringa stl amd s172 are equal you ofen Sethe following consti The exclamation mark indicates the boolean NOT Thus the expression evalustes to TRUE ony if strcmp ur 0 Expressions are combined of both termy and operator The fist could be constants ables or expesions From the later C offen all operators known Irom oiher Enguages However offers some operators which could be viewed as abbreviations to combinations of ther operators Table 7 3 lis availabe operators The second column ows their priority where stall numbers indicate higher priority and sume numbers ame priority The ast column ss the order of evaluation You seal know mast of these operators However some azed some mane description First of al notice that the binary Boolean operators lt and 1 are of lower priority than the equality operators and Consequently i you want to cheek for bit patterns a in You must enclose the binary operation into parenthesis var Nec ao a T rine a m0 m EN T Element sekretar Tom kie i 2 Eolea NOT om rit Tinry NOT oo le I Pot Prine Torn right 2 Pest Prokecrem
145. t e g the statement Evaluates the expression on the right hand side of the equals sign using the ure values af Sense tans and assigns tbe resulting Value wo the variable 10 Layout af the programs is quite arbitrary Le new lines spaces ete can be inserted wherever desired and will be ignored by the compiler The peime aim of tional spaces new lines ete is to make th program more readable However Supertious spaces o new lines mast nor be imeried in words like nain cout ia able names or in tings ness you actually want tbem printed 64 Variables A variable isthe name used for the quantities which are manipulated by a computer program For example a program that reade a series of numbers and sums them wil Pave To ave a variable to represent each numbers it i elered and a variable Lo represent the sum of the numbers In onder to distinguish between different variables they must be given identifiers names which diiaguish them Trom all other variabies This is simila to elementary algebras When one is taught to write Let stand for the acceleration of the boy Here Ais an enter forthe value of the acceleration The rules of C for valki identifiers state An identifier mst stan with a eter Consist only of leers the digits 0 9 or the underscore symbol ot be a reserved word Reserved words are otherwise valid idemifers that have special significance to C For The purposes of C gt identifiers the underscore sym
146. tatement in which the statement following theese is itself an se tao statement T x is ess than zero dhen qn tatty however i iL is not less than ero tbe stern following the a22 is executed In that case if x x equal to zero then gu inset 1o zero amd otherwise itis seto T Novice programmer often use a sequence of statements rather than use a nested 1na statement That is they write the above in the logically equivalent form Tu Nec This version is not recommended since it does not make it clear that only one of the assignment statements will be executed far a given value of x Akso it inefficient since AN throe conditions are always tested M nesting is carried out to too deep a level and indenting is not consistent then deeply ested or 12 e130 statements can be confusing 1o read and interes important 1 mote that am e10 alaya belongs t the closest 1 without an ee When writing nested ie ezse statements to choose between several alternatives use some consistent Layout such as the following c condition gt Satemene tae tt condition 1 Wile ar c coon Assume that eal variable x is known whe peter than or equal to zero and less than one The following multiple choice decision increment count if 0 a 02s increments councs it 025 Cos inerments coumta it 03 a 075 and increments coun 08 i i Note how the onring ofthe tests here has allowed the simplification of the conditions For example whe
147. te program iS terminated The value Ith is returned indicts to the operating system that the program Was terminated with am error condition As the ss program now returns Valu it mast be declared at having the type nether than ois Having connected the extemal fles to the streams any inpuoutp fom these streams Will ten be rma the connected files In the following example two streams are declared on for input called ins and another for output called s22 These streams are then connected to fles with names Sse 43t and sensi respectively by All aches to these files now uses the declared stream names ine and outs and the inpuoutpue operators lt lt and gt Inpuroutput manipulators can also be used on the ouput steam Ths data item is entered from the stream by nd results are output to the stream out by Tier Neic 11 3Testing tor end o e Inthe above the functions open and 311 have been attached 1o a stream name Another fanetion that cam be artached 1o a stream name isthe end of file condition o This condition is set nae when an attempt is made to read beyond the end of a file otherwise i inert false Unlike some other languages the caf file character is actually entered and the aor Tanerion seus tue when i is entered For example to read values from a Sle and evaluate teir average then the following cade could be used Ties Nec Note that atthe end the streams ins
148. ter n indicating bow many ines have to be Slipped as follows As before this fanerion does not senur a value hence it is declared as having type vesa It teow takes an integer parameter n which indicates tne numberof lines to be skipped The Parameter list hen consiste of a type and a name foe this formal parameter Inside the Body ofthe function enclosed in lop contol variable is declared This variable iKa local variable tothe function Algal variable defined within the body of the Ta Neic function has no meaning o value except within the body of the function It ean use an identifier name that is sed elsewhere in he program without there being any confusion twit that variable Thus changing the value of the local variable sin the function sip SIN not affect the value of any other variable used elsewhere in the program Similarly hanging the value of a variable 1 used elsewhere in the program will nor affect the Value ofthe ocal viable inst The function is called inthe same manner as axtpcheee above but a value must be given far the parameter n Tal he following cal are acceptable however the call would not be acceptable because the actual parameter type mist match the formal parameter type given in the definition of the function In writing the function prototype for a function with parameters it is not necessary to sil he formal names given to the parameters of the Fanetion only thi types Thus 2 suitable functi
149. the cout steam output as required Nic Chapter 8 Statements Statements 8 8 1The statement In onder to produce sorts it must be posible 1o select the next statement 1o execut am the basis of some conn The tx siemen is the simplest form of condiional oF election sstement in Ce The following 1 statement Neic will print out the message rn waive o2 x is poss ve Wis positive The general form of he statement is contin Where condition is any valid logical expression or a soo variable The statement can bea Single Cr statement of any Kind and ena be ened by a semi colon I can also be 2 compound statement Which is a Sequence of statements enclosed in left and sight braces feats as a single salement A semi colon does not follow the closing right bence 841 1Examples of statements The following 5e statement adds x to a variable sun if x is positive The following 1z statement abo ads x 19 su ba in aon ht als 1 io a count of tive numbers held in the variable poscous The statements within a compound statement can be any C statements In particular another statement could be iced For example to print a message if a quantity i epi and a father mensage i no overdratt has Deen arranged Neic Inti ease the same effect could have been achieved using wo se stern and a more complex set af conditions 8 2The if else Statement A simple state
150. the following ponian af C program Tis Neic Note the use af the logical operator not operating on the boolean value to invert its tra value Another way of controlling the lop is to assign the vale of the condition directly 1o ccone At fimt sighi this may appear sirange but the condition iS already being alate as either Eeue or arae x0 makes sense to replace the cele aatement vith 6 3Example Program Student Mark Processing 2 The program writen using a ao un e lop The o ste loop would be This is not completely equivalent to the wie statement version Consider what happens iE the user initially enters a negative candidate number ihey would be surprised 10 then ary Nec be asked for farther data and another candidate uber Mf ther a least one candidate then the two versions are equivalent 8 7The for statement Frequently eopramming it is necessary to execute a statement a fixed number of times fora a consol variable takes a sequence of values For example consider the following se ofa vn 1 statement w output the numbers v 10 In tnis case the integer variable is useat to contol the mumiber of imes the loop is executed In such a while loop three processes my be distinguished Initialization initialize the control variable 2 1 Test expression evaluate the vuh value of an expresion 2 lt 10 Update expression update the value of the conul variable before exec
151. the moment the most suitable seting of the iosflags for ouput are ixoa and The following portion of Cot woul ouput at i in zinea format with two places after the point and te point displayed Without the so flag set 1o snonconae would have been printed as If the decimal pas have to be aligned then the fil width has m be set This done using the setw manipulator bich takes a single parameter which indicates the width of field n which the output alue is be placed The value is placed right justified in the field The field width email effect only for the mext data item displayed Thus if the lines were added othe above portion of code the output would be Note 1 The file sonan ip t must be included if the above manipulators are 10 be we There ave many more facies available by using inpuouiput manipulators but the Kaele kap earann ikiden that produce sense formating of ouput in most cases Note 2 The output width i veset othe default after every variable is output so that it was necessary to use sc 17 tie once before each variable that was opu 79 Example Program Tabulation of sin functor The following example program tabulstes values af th sin function using manipulators tole he output eal in columns In this case aks values O12 16 Neic produces nicely aligned tubular ouput as follows Note how the soasige were set at the beginning bu that the precision and with were set individually in
152. the program should output the minimum positive valbe entered the maximum postive value entered and the Farage of the positive values entered I there i mo data entry ihe user fmt a negative number initially then the program should oupa a Pesage indicating that no data has been entered Neic In this program as each umber i entered it must be compared with zero to check ii is The sentinel Value that terminates input Each postive number must be added 10 an accumulated sum and a count of the number of numbers entered must be incremented 30 The average can be found Also each positive number entered must be compared with the unimurninaaimu entered so Far and i necessary these values are updated This meann that while the entered number is positive i must e processed Thus a Tist tert at an algorithm might be As usual the fist thing done in this algorithm isan instiatizo step This will be Expanded Inter once the details of the est of the algorithm have been finalized The pressas vatos statement mast carry out various aks The sum of the input data ales ust be acumulted and a count of the numberof values entered must be incremented The data Value read in mast be compared with the minimum so far input and i acess these values are updated Hence the expansion of proces vatu it Looking at this expansion it is obvious that prior to the fist entry 1o the loop the following variables require iniilization 1 a va
153. the return or enter key has been pressed Ir more values are supplied than are required to give each variable in the input lista value the unused values wil be used for any subsequent input statements using cin For example given the following declarations Neic the user could enter 1o assign 23 1o cune 68 1 to vazos and 3 to n There is no indication in the data of Which value is to be associated with which variables the order of the data stems mast orrespond to the order of the variables ia the input list Spaces or new lines should Separate the data lema on input Any numberof these will be skipped over before or Teween data iem Ths the Input above could equally well have been entered an The following statement outputs te curent value of the variable coust to th output seam ous which is usually associated with the monitor The value will be printed on The curren ine of ouput saring immediately after any previous output The general form of a statement to perform output using the output stream cou is cout outputs Where outfit of variables constants or character suings n quotation marks ach preceded bythe output operator lt lt The output operator displays the value of the item that follows it The values are displayed in the order in wbich they appear in the output A new line is taken if the special end of line character cot is Output H an oat is mot output the ouput line will ether be chopped off at 1e ight band edge
154. the variable resit It is important to none Ihat the Value assigned to rel must be of the same type srs The expression can be a single variable a single constant or involve variables and constants combined by the arithmetic operators Listed below Rounded brackets 1 may Also be used in matched pis in expressions to dicate the onler of evaluation ition subeaction mukiplication division roninde after division modulus For example The type ofthe operandi of an arithmetic operator is important The following rules apply if both operands are of type int then the result is of type int if either operand or both are of type Mat then the result is of type float ifthe expression evaluates to type int and the sesul variable i of type float then the ic wll be convened 1o an equivalent 2552 before asignmeat 1o the result sible Te expression evaluates o type float and the result variable i of type In then the ios Will be converted aan usually by rounding towards zero before assignment 1o he result variable The last rule means that itis quite easy 1o lose accuracy in an assignment statement As already noted the type ofthe value assigned must be the same type as the variable 10 wiek it is assigned Hence in the following example in which is a variable of type io the compiler will insert cade to convert the value 3 5 to an integer before carrying ou the assignment Hence the alue 3 will be assigned Io t
155. to ite if a above closing braces are aligned with the corresponding opening brace 1 However other conventions are used forthe Lyout of braces in textbooks and oiher C programmers programs Also additonal pace new ine etc can also be used to take programs more readable The important thing is 1o adopt one of the standard conventions and sick W it consisteniy 69 Input and Output Input and ouput use the input stream ci and the output stream cou The ingur ream can is usually associated with the Keyboard and the output seam sou is usually associated with The monitor The following statement waits for a number to be entered from the keyboard and assigns itio the variable ante The general form of a statement to perform input using the input aream cin i inputs hee inp is ist of identifiers each identifier preceded by the Input operator gt gt Thaw would take the next two values entered by the user and assign the vale ofthe first one to The variable andthe second to the variable 2 The program mast read a value for each viable n the input before it executes any more ttereate The order ia wbich the values are entered mast correspond ta the order fhe variables in the input ist and they mast be of the samme type 3b the corresponding Variable They should be separated by spaces Normally the C system will not pass ny vales to the variables in the input ist until a complete line af input has been ead ie umil
156. uces a table of x amd osx as e takes values O 1o 90 degrees in steps of degrees Note that the Cet sin function takes an argument in fading not in degrees In the programa below san tendon veturas the sine of an angle Tsaar expressed in radians T Neic Note that the mathematical constant i defined in the mathematical library atcp 8 54Example whe lop Average Minimum and Maximum Caleulatie A user is wo enter positive float values from the keyboard when prompted by the program To signal end of taut the user enters a negative integer When data entry Bas Terminated The program should ouput the minimum Value entered the maximem vale entered and the average of the positive Values entered If there iso data enny the user enters a epave number initially then th program should output a message indicating that mo data has been entered The ial version ofthe algorithm was The above algorithms can be writen in C as follows Tm Neic 1 5 Example Program Student mark processing Ast of marks is available for a elass of students For each student the following details fre available Heeseong for abject 1 2 percentage couraevors mark for subject E ir Stacinstion ance tor abject 2 2 Eitiotiage couremect wart tor sunject 2 A program is regi which wil read in the marks at above for each student and will output for each student in one line the above information weth
157. un be produced from nwo integers amand a a follows m n Zen mtn Tm Nec To generate a list of Pythagorean wipes could be allowed to take values fom is minimum posible value 2 up 10 some maximum value emered by the user For each Value of fom L up wth corresponding riple could then be evaluated and output An algorithmic description for this is This description uses a cor loop a looping construct that repeats th lop statement as some control variable takes a sequence of values Also note that one for loop is nested inside another tnis is very common From this description the following C progam i easily produce Tm Nic Chapter 9 Functions Functions 9 4 Tup down desig using Functions Nec Sine an algorithm has already been produced which outputs the wage given the hours worked and the hourly rate the description of this could mow be used a the expansion of proasce uage This re use of am algorithmn from a previous program saves Ume in developing an algorithm again and if the algorithm hat been previously tested and ecified w be comeet also reduces dhe chances of eror The best mechanism for this re ase of an algorithm so incorporate 1t inno a funetion The function is given a name and s supplied withthe input parameters or arguments ofthe problem and turn the results as output parameters Thus the description for the calculation af the wage could be placed in a
158. ust allocate memory and Copy the individual elements In ou class Paint we therefore al hird constructor Wich ske care feat copying values fram one object to the newly crested one 76 Neic The thin constructor takes a constant reference wan object af class Paint as an argument and assigna and the corresponding values of the provided object This type af constructor is so important that it has its own aame copy constructor Ii ight recommended thut you provide for each of your classes such a constructor even if it ixa simple asin our example The copy costucto is called in the following eases With heip of constructors we have fulfilled one of our requirements of implementation of abstract dara Types Iniislization at definition tine We sill ped a mechanism which Automatically destroys an object when it gets invalid for example because of leaving its scope Therefore clases cun define detractors 623 Destructors Consider a elass List Elements of the Hist are dynamicsily appended and removed The consructor helpt us in creating an initial empty lst However when we leave the scope ftthe definition of a list object we must ensure that the allocated memory is released We therefore define a special method called destructor which is called onee for each objec at its destruction ume Destruction of objects take place when the object leaves its scope of definition or is explicitly destroyed The Later happens
159. ut and output On output iKa number i oo large to display n six digis then scientie notation will be used by default For example 1234367834 migla be output as 28457607 The fira manipulator considered is setiosflags this allows the output of flouting point mambers tobe fixed fixed format ie no sie notation sclentifie_scientiie notation Shawpoint displays decimal point and wailing zeros The ags that are to be set are specified in the set tont aga manipulator as follows sstsoetiage 1108 flagname M mose han one fg is to be set ten another ice flagname can be included separated bya from the other sening in the above call Thus the following output statement would set fixed format wth the decimal point displayed This would ensure that a number Like 1 0 would be displayed as 10 rather than as 1 These Dags remain in efect unl explicitiy changed Nec Another useful manipulator is the setprelsion manipulator tis takes one parameter Which indiestes the number of decimal places of aceuracy to be printed This accuracy eam in effect ual itis reset The serorcetoson manipulator may be used wien bone of the iosflags have been set However thre is some confsion over what constitutes precision some compilers will produce mis in al and others digits afler the point when serproct sonim is used on is own However if iis used after the fags rixa or seten 121e hae been set it will produce n digits afier the decimal point For
160. valuation af some condition 0 4 10 Polymorphism Polymorphism allows an entity dor example variable function or object to tke a city of representations Therefore we have to distinguish different types of Polymorphism which wll e outlined bere The fit type i similar to de concept of dynamic binding Here the type of a variable depends on its content Thus it type depends on the contentat a specifie Ume sev is integer Y Pe use v as integer 7 abe equated to siring 7 Puse var sing Definition Polymorphism 1 The concept of dynamic binding allows a variable to tke different types dependent on he content a a particular tme This abiiy of a variable called polymorphism Another type of polymorphism can be defined for functions For example suppose you want define a function lt EMDisNall Which returns TRUE if its argument 0 2220 nd FALSE otherwise For inleger numbers this is easy boolean Nalin Wu 0 thes stim TRUE ee tun FALSE nit However if we want to check this for real numbers we should use another comparison dae ta the precision problem boolean Nulled ie O01 sade 0 99 then stim TRUE he Nec stun FALSE it In both cases we want the function to have the name is Nu In programming languages Without polymorphism for functions we cannot declare these two functions because th ame is Nall would be doubly defined Without polymorphism for fanetions doubly defin
161. when we dynamically allocate an object and fees it when it is no longer needed Desrctrs are declared similar 1o const Tha they also use the name prefixed by a ilde of te defining clas Nec Destructors take no arguments I is even invalid 1o define one because destructor are implicily called at destruction time You have mo chance o specify actual arguments 63 Simple C Program Before looking at how to write C programs consider the following simple example program The folowing points should be noted in the above program n Neic Any text fom the symbols until the end of the inet ignored by the compile Th fil allows the programmer to inert Comments in the program Every program shoud atleast have a comment indicating the programmers name when e was written and wiat the program actually does Any program that is not very simple shold also ave farther comments indian th major seps carried out nd explaining ay particularly complex piece of programming This is essential ithe program hast be amended or corrected sta Dater date The line must start in column one It causes the compiler to include the text of the named fle Cin tis ase 3052 raan 1 in the program at this point The file ose fash 1S a system supplied file which has definitions in IL which are required if the rogram is going to use seam input or oput Al your programs will include this file This sistemen is a compiler direct
162. wo parts or The circle and triangle ar purt of your ogo We ilustrate this in Figure 53 ene putes cee te 454 Has A relationship This relationship i jast the inverse version of the ptf relationship Therefore we can easily add this relationship to the part of station by adding arrows direction Figure 54 Lowes purest oe a Nec 46 Inheritance 46 1 Inheritance With inheritance we are able 10 make use of the akin and ia relationship As deseribed there classes Which ate rink another class share properties of the late I our point amd circle example we can define a cicle which ners rom point hss Circle inherits all data elements and methods from point There is no need 1o define thom twice We just use already existing and wellknown data and method definitions On the objet evel we are now able to use a irele just as we would use a poiat because a circle iva point For example we can define circle object and set i center point condi sa also implies that we can use a cule everywhere where a point is expected For example you can write a fanetion o method a uve which should move a pointin direction As a circle inert from a point you can use this function with cele argument to move is cemer point and hence he whole circle Lets uy to formalize the terma inheritance Definition dunheritanee Inheritance is he mechanism wich allens a elass A t inherit
163. you have learned about the requirements far the product All the design decisions you made how to modularize wbich ADTS 10 use which algorithms to use and why you made hose decisions AI the tes euses You have thought of and all the test data you have used A the features that need t0 he decribed in online heip G availabe or wer manuals if available M is probably also worth keeping multiple versions of the source code fen you will iadace bugs or other problems ato the code and having a copy of a previous version to back up wean save a great deal of time and effort rediscovering th right way todo Nic Chapter 2 A Survey of Programming Techniques Neic This chapter is a shot survey of programming techniques We use a simple example to sate the particular properties and to point out their main ideas and problems Roughly speaking we can distinguish the following learning curve of someone who Mearns to program Unstructured programming Procedural programming Modular programming a Object onented programming 2 1 Unstructured Program Usually people start learning programming by witing small and simple programs consisting only of one maia program Hee main program stands for a sequence of commands or statements which modify data which i global hroughout the Whole program We can ilustrate tais as shown a figure 2 1 below As you shouid all know these programming techagues provide em

Download Pdf Manuals

image

Related Search

Related Contents

rs-232c communication board fx1n-232  IMPORTANT SAFETY INSTRUCTIONS  GDM-500PS/500PST/500PST9  

Copyright © All rights reserved.
Failed to retrieve file