You are on page 1of 120
C++ Course Guide © University of Wollongong / Singapore Institute of Management All Rights Reserved, 2006 ‘Composed by: Kerie Lee Hats snd Willy Susilo School of information Technology & Computer Science University of Wollongong, Austria ‘This document sto accompany UoW programs ony: Bacher of IT (Computing). Bachelor of Computer Science (Digital System Security specialisation) and Bachelor of Computer Science (Multimedia and Game Development specialisation) Disclaimer: This document must not be reproduced without permission from the Schoo! of Information Tectnology & Computer Science, Univesity 9f Wollongong, Aust and Singapore Institute of Maragement. Prefice Basic Biements of Co ‘What is Program? Dasies of aC Progra Data Typo = Variable Declaration Statement Assignment Statement. Expressions... Expressions using Avtetc Operators Aritumetc Expressions wih ltogee Operands. ‘Aritimetic Expresios with Fleating-Pint Operands : ‘ite Een Wi Med Ope dni Type Cavern 1) signet Senet and inp Tpe Covers. Explicit Type Conversion... Outpt = Selecon switch Sutement ‘Valu Range Repetition ~ for Statement. ‘Repetition - whi le Statement Repetition ~ do while Statement. User-Defined Functions. Pointer Data Type and Pointer Varabic. Dect De Reining nd Aight ‘With Relational Opeatre Other Operations on Points Varies. ‘Void Pointers as Function Parameters. Pointers to Function. Proface “This munis designed as a introdution tothe C++ programming language. offers a sc understanding of C+ programming concep and stax which, enables the student to further sud the content a higher lve. In order to complete this manual the student will equre acces to compiler and a simple text editor. Word processing packages are at suitable. fink tthe Quincy Iniegrated Development Envizoemant Which contains both the comer ander can be find blow. Use the following lnk to dovnload Quincy im ‘UserName: exc Password: willy Quincy - Step by Step How to create & compile a CPP program with Quincy? ‘This simple tutorial will show you step-by-step on how youcan create and compile «CPP program with Quincy. ‘You need to install Quincy in your computer and follow the following tutorial Let’ assume that you will write avery simple "Hello Worla” program. 3. Select "Cr+ Source File” and click “OK’ 4. Type the "C++ code” in the window. For example, font &¢ “Hate Bort” [cout << Plonting:poant oparandas* << and ‘+ Format he output for Noting point vas. Ad the following code to in, whch uses the unary arithmetic operators: "+ urpuni sereen ihe values of expressions using the unary arithmetic operator. ‘Add the following code to man, which uses he binary arithmee opertors Sout ce "6.07 2.92" ce G0 / 2.0 ce analy ‘+ Output to sree the values of expressions using the binuy arithmetic operators, compite Oe program. 2 ‘This statement is illegal in C++ as the modulus (8) operator i only applicable to integer ‘types. Delete the following line of code to remove the er, Ck SARE RE RE AREER EEO ‘compile and un the program ‘close he fi ‘Arithmetic Expressions with Mixed Operands and Implicit Type Conversion ‘A requirement of C+ arithmetic expressions is hat both operands for soch arithmetic ‘pert be the same type. Ihe operand are different he compiler will convert one sie of the operation to the ype of the otber side, This know as ype coercion. The ‘conversions possible for ardimetis expression are eur 3 sae / fone / doume Sime 3 etoae /dounte ‘Create a source file for a C+ program named “nixedBxpres following code: ris cpp" and ad the ‘Sinotugs clonanip> t “Define the main funtion, The include statement below allows the use of formating functions fo output operations. ‘Add the folowing code to ma fined | sont ahowpoine) + Allow formated ouput (i e discussed etl ate) Ad the following code to a oot evga s& ce 6.0/4 emt even /as + | ‘ion. pp" and add , te "Define the man function, ‘The conversions posible for asjgnment statements ae: cur & dae € shar / float / doute © ne /‘aouble / cane (acts vale) © toe / flow / char (ascii valve) 4 the Following code om To ‘+ Declare variable ¢roae variable and asin an nt val ot Likewise, the compile an convert floating-point types to inter types similaly ‘A the following code to mai Declare an int arable and assign tit lating pint ale Comptia the progr (Werning] converting to int) fren “doable “The waming is produced because a double type is being atsigned 1 an ne ype The compiler wil rescve his warning self by trneting the valu being assigned. Thats )) opeeatris avilable o explicitly cast one type another and can be used io eat any ofthe built-in types to another bulla type. The type to which the datas tobe cast placed inside the <> brackets andthe valet be converted [placed inside the () bracket. It is imporant vo note tha th valve ofthe parameter, inside the () brackets is never altered |Add the folowing code to ma: + Declare a 20a variable and et its vale and declare an nt variable and assign to tthe cast vale ofthe Eioat vail, When using the seatic_exet<>() operator, wanings about ype conversions ae 00 longer displayed and the variable var ites never altered. The value ofthe parameter is retrieved, converted to the required type and ths is returd by the operation (and Ines wed accordingly) ‘A cast may also be performed on char dan ‘Ad the following code mas: ‘+ Declare a char varable and assign tthe vale“ then output to screen the cat vale of ta an int {is important to understand thatthe cha type is stored interaly an integral vale "Thais the sel value of the character stored in bit binary. Ta, athe satement ‘An implicit type conversion occurs andthe ‘a is converted loan Sat and the value #7 isansignedo caver. Add the following code to main To; ‘Assign the value 90 fo chivas and output oseoen the ctv of tas an int compile and eu the program Although char variables store data using the acl valve (inege, when ouputing the ‘ale, actu characters are produce, Programming Exercise: ‘Write a program to perform some simple arithmetic als with mined operands and ontpe the results, 1. Create a C+ program named 2. Add the main faction and the appropriate incide Slt) 3 Define thera function and do the following: “Declare one ‘nt variable, giving some inal vale (his can be whatever yoo lke). 5, Declare one cicst variable, giving it some intl value, {6 Add the appropiate output Satements as seen stove to output the ‘alu of the ow variables, 7. Declare third eloat variable to hold the result of some simple srthmetis caleltions performed onthe variables, 8 Perform the following calculations using the >the szeam extraction operator and reqies two operands ‘cin is always the lf side operand and ithe input tram, ‘vars the right side operand andi the variable to rosie ing meeer on integer ool ‘he integer 12 300 eter a flonting-point vaiue: (56.8) | Se"Zusstingvpotat value se se.8 ‘Ta values onoased Sn the } 2 uae Sopot. this omant will When a ein statement is exerted the program waits for dua to be entered vie the ‘eyboard and the eater key pressed, ‘The defttt behaviour of the steam extraction (9>) operator it to skip white-space characters. That i, it ignores leading whitespace and uses traling white-space 0 terminate each apa operation. White space characters include: abe + newline? ‘AIT input data i stored in the input buffer a 9 sequence of charters. That is every Key pressed on the Leyhoar willbe red in he input for incladng de mtu hey. For each input operation using the operator (>), afte ignoring leading white-space, ll sracters willbe extracted fom the input buffer until either a shite spece character or sfarecter which does not match the varble type i encountered All characters which ae hot extracted will remain inthe input buffer and will be extraed upon the next input operation. Thus + Ifthe input variable i an éne type only the sequence of numeral characters (01 23456789) arovalid Thus, "(spae) ora is encountered, extraction of characters will erminate and the exacted characters wll be converted to tele, Unteger valu and assigned to the variable. For example, the input daa i (© “1 willbe extracted and converted to the inter vale 1 then assigned tothe variable 12" wil be exacted and converted tthe integer valu [12], then assigned to the variable. ‘© "123" willbe exacted and converted tothe ineger value (13 hen assigned othe variable. © 0" willbe extracted and converted to the integer va [0] then ‘signed tothe viable and 123" wil ean in he inet bute, ‘© “12” willbe extracted and converted tothe integer vale (12] then assigned to the variable and the wil remain in inpat bute. © 12 “1 wile extracted and convened to he integer vale (1) then signe tothe variable and" 2" wil remain inthe input bate, © Ifthe input variable is & char type, any non-whitespece character is vali including the eumeralchracies. Fr example, ifthe inp is © °F willbe extracted and assgne to the variable (ac SO). © 4 ‘willbe extcted and assigned tothe variable, © “J will extracted and assigned othe arise, © ~ willbe extracted and assigned tothe variable. (© abe 2 willbe exacted and assigned tthe variable nd “abe wll remain inthe input buffer ‘+ Ifthe input vaible isa frost doubt type, any sequence of characters which ane interpreted a6 2 ating point value il be exacted and converted 0 their loatingpoint value and asigned to the variable: Thee include the numeral characters and the character". For example ifthe input © “2 willbe extracted and converted to the floating-point value [2.0 then esigned tothe variable © "2" Wile exraced and converted to the owing point value [2.0] then assigned to the variable. “2.5 wil be exacted and converted to the Mosting point ‘ale [25] hen assigned to the varie (© 2a 2" willbe exacted and converted tthe lostng-pint value (2.0) then assigned tothe variable." wl remain i the input baer, '© 1345.00 1" will be extracted and convened tothe floating-point valve 11.0) then assigned to the variable. 345.00" wl remain in the inp bate, ‘The seam extraction operator (>) can be contented. [Ad the foloming cde: a 1+ Ressve input into the tv variables. (compte ne un the program. ae invegee 100 oe? (100) During the lst input operation, evea thre was no whitespace separating the input ‘alts, the compiler extrac the data that it could match tothe specific types and hus, 21. was tred Vax," Was stored in ar and 20” was tore in Var ‘Programming Exercise: ‘Weite a program that calculates the tax owing for a small busines. The tax amount owing is 17% on net profi Create a C+ program named “pact Lcetxescisernput.con” ‘Ad the ma‘ function and the appeopit include ts Define the main function and do the following Declare font variables to hold the values for gross sales, gross expenses, net profit, tx owing Receive fom ser input the values for gost sales and gros expense, Cleat the net profit sales less expenses). Calculate the tax owing (et profit times tx percentage) ‘Outpt the sulin the flowing fama ‘Gross Seles: “vaio (Gross Expenses: NaProft Be sure to replace withthe vale of the respective varibles. ‘An example of coe to output in tabular formate given below cout "Gross Sales ‘ce grosSeles << endl 11-Compile and ran the program to ensure thatthe code is logically ‘correct. That iit poforms the required task, Standard Output Outpt operations have previously bees introduced end now will be dscused in detail Create a file named “output . cpp" and ad the following coe: Toi Define the mata fuetion, Notice the ine ream i included ina program an output seam object named cout i automatically create wo allow ouput operations to the sandr outpt(asually sren) the include statement is ising ftom a program the out steam objet, cout, cannot ‘be sed andthe program will produce ax ero during compilzion if out i accessed, Output can be performed using the steam insertion (ce) operator which is binary operate. ‘+The ef operand isthe ouput stream objec. ‘The right operand isthe data to be output. This canbe ether the vale of a variable ors constant, oF a suing of character, refered to asa sring ier Aa he following cadet ma ogi atring outpet operation”) + Output to seen a sting of ext ‘The statement will ouput a sequence of character alld arin. All ofthe characters appearing between the two quotes (*) wil be ser to the ouput bff to be printed to 2s ‘compte and fun the program. ‘Tala Ue a wlngie otring output operation [Notice thar the quotes) do not appear inthe cutpt. This is hecase they have epcia! ‘meaning in this content. That, the belong abd the end of Sting IF quotes are to be 8 part of the ouput string, they mus be preceded withthe escape character. This is Frown as an escape sequence, Commodly used escape sequences \e | Newtine | Cursor moves tothe begining of the net ie \e) Tab ‘Cursor moves to he next lab sop {We Backspace | Cursor moves tothe leone sacs X=] Rowm | Cursor moves to bginning of uett ine. W] Bact | Oupuran \"] Sinai Quote [ Oupara® \" [Double uate | Output a” Modify the semen cout << “Thin Ae @ single string output opasation." ] To the following + Ouputtosereen svn of text that icles the quotation marks. ‘When the compiler encounters th escape character in sing ¢ wets the next character wth special meaning Inthe case of \, I ftrpet the itenlly and includes fin the ‘utp string, Compile and ran the Progra. Sais tes single jing output operation = Ad the following coe o mai: + Output sreen another sting Coupite and an the progean TEES fg dinate string outpt qerstions” io Is Os a "Notice thatthe output is all onthe same line. This is becuse cout places all output inthe ‘output bufer one characte aftr another If out i o be placed onthe next in, the newline character *\n" mus also be placed inthe buffer atthe appeoprat place. ‘Medi the line of code: cout << "\"this is a single string output operation. \"") To the flowing: cout << “\'thie se « cungle string output operation WW"? ] ‘+ Oust to seren the to strings, which wll be separated ty newline character. ‘Whenever the newline crater is encountered, the next outpt will begin on the next line. ‘Bile"se"che next tine of outers ‘Te stream insertion opuator canbe coneatenated, ‘Ad te fllowing code to main ‘cout << "\athis output string bas * << « To * Output to sereen a concatenated string. Another way to insert the new-line characte nto the ouput stream is to we the stream ‘manipulator en. It works by insring a ew-line characte int the output Bue and then Mushing th Buffer. Thais, send the output direct to the out device ‘his Le s siagie string cotgut operation Formatted Output “The output szeamcou is defined with some default behaviour for lstng-point value, Creat afilenamed "coraattedoutput .epp” and ad the follwing code Aud th following code oa + Output to sereen an example ofthe defiult bebaviour of e>ue (otic thatthe desimal point not aiplayed. In order to free the desma pois, the Add the following code to mae 4 Set the stream manipulator to force the decimal point to display and ouput 2 vale Compe and in the progres. Soe thatthe decimal point is now displayed. Alo, notice tat there are two decimal places afer th decimal pin, That is because the precision inst by default to & digs in fot ‘Sethe precision to 4 digs and ouput a Before, then t 7 and output ‘The defult behaviour set-precteson( ist apply the precision tothe mmber of digits isplayed in total Tis notes tose betore and sir the decinel pont Sieets reckon to «Hasso Ss.” “Thus the precision isto print igs, What f the mumbo is lrgr than Wis? ‘A the following code to main: cout << 78 digit munber: ssssssss. = Tos ‘+ Output values wih 7 and 8 digits ttt the pression ‘Compile and rn the program ‘Shing te Goeaait behaviour’ aua.e anne Sceting showpeunt Hass HEi.00 ‘The seven digit number pied in fall asthe precision is st w 7, however, the 8 digit ‘number is act Is being displayed in scientific notation, which the def, and occurs when the number isto large forthe precision valu. In order wo change this to xed decimal notation, the £00 manipulaior i ured |Add the folowing ode to main SSE Seeley eee sssssaas. + + Setthe output fixed dsimal notation and output vale, (Compile and tum the program Setting showpoint Ssss.0 565.00 Sitting peecision to 7) faa8.0aas8.e00 Notice now thatthe notation isin Hed decimal place instead of sient, however, the precision no applies tothe digs afer the decimal place. Tis is what happens when fixed is used. The precision now applies tothe places arte dacimal point. So fr, the ouput has ben formated int columns by hart-coting the spaces. This can also be achieved by sing the ects) function which takes an integer parameter tht i {he wid ofthe output colam, ‘The sett) function ses the width ofthe nex ouput tem ony, Thai, outputs the data in column that is the specie vale characters wide, yo 1 Ifthe sizeof the dans less than the vale given, the remaining spaces ae filled wth lank spaces. + Ifthe sizeof the data is ager than the valve given, the specified size is over- "idden by the actu sae. + Thefinction set (only applies tothe next cups item, “Modify the current code within nai to the following: ‘cout << set (39) Gross Expenses. $evale> Nat Profit Seva ‘Tax Owings Sevag 1 should te replaced by the values ofthe reapetve variables, ‘Format the outpt to two decimal places. 350050 or 2500-00 4 Use the sot) function ost the with ofeach tpt item. The." shoul be fled using the 26511) fenton, 5. Compile and run the program to ensure thatthe code is logically ‘comet. That iit performs the equred task. Control Structures ‘Cade ean be exeute in oe of tree ways ‘+ Soqusntally~ Sttement(s) are exceued oe after anothr in top-down approach Selectively - Sutemen() are exeuted by making» choice. Do this, OR do that. + Repsitvely - Statements are exeuted repeatedly “Thus fr, the code has ben Sequel. However, a times the progsemmer may require ‘extn code to be executed based upon some certain condition being met. Osher tines, the cerain code will be repeatedly executed, Two specific contol strctres ae used 1 implemen section and repetition Relational Operations The condition ypon which a selection oropetion structure it bed, most fn i the result of felaional operation, The relational operator re: = | Equatto =| Nocequal te = | Less than| “=| Less than or equ v0 > | eater than Each ofthe relational operators is binary operator. When wed in an expression, the result of relational operation is ete 1 ae) orO (fale) ite the condition etre, or itis fle Crest file named “relat ionaloperat one cpp" anda the following code soe asin 0 Tor Define the main function ‘Add the following code to mass: 4 Serer SSS 05 2) S cea secret atsata SSa ‘The code above uss the relational operators with int ype. Relational operators also work any ofthe built-in types and the operands can be of eed pes, Ad the following code to main out tnpet) ‘Sout 0 64 septa > 0) Sf Gace Input ce An Lees than * 2 << end feiss 1 (inpuet > inpatay 1 GRRE SS AAR o> A eg Ge © ce Spats ce as ‘+ Testif tnpues is grater than © AND sep the code inside ofthe () Consider the expression: Gapeti > 0 ae inet >] In ode for the expression to be evaluated as re, bth expressions on each side ofthe rust be ts. That is, zpu must be greater than Od Sop mist be great tha 0 Teethers sas, the eire expression i fale, Isgreater than 0 and iftrue execute ‘compile and nn the progeen. Encar Sg Setegng wnt 0 385) Alternatively, the logical operator (|) canbe used. Mos the nested and cscaded statements to 4 (enpoes < saps) pout OF * OT ieee om In order for cco be evaluated ast, onl one expression on eer side ofthe || mst be tove. Thais, inpuc must be greater than OR input mustbe greater than Of Both ses are fle the entire exprosion ae, Compile and ean the progr. “peapar vatonas (0 3237 \ Ing asthe condition of an = statement evaluates oa negra value, the expression il eveiate to tr (1) if the value is nom-zero, otherwise it wil be fale (0). Modi the nested and cascaded statements to ae tee at ( Saputt > inpue2) ‘Sout S<‘tnputs ce" is greater than * <¢ inputs fe than * << apne Sout Ae equ eo © << Lnputz ‘out << “impute mast not be 01 Tapa In this code, the variables tnpue3 and snput ar being incremented alr being used in ‘he evaluation. If the left side ofthe 11 expression is tus the right side will not be exseuted. Hence, the variable epi will aever be incementd. Ths: ‘Be cael about having code that ha side-effect in logical expresons. Logical expressions are evaluated left to sight and ee has a higher precedence than 1 which hasahigher precedence than the relational operators (< <= > >= == =I Programming Exerle: ‘Extend the program from the previows example, validae the values input bythe user and only continue if the values are valid by using eke statements (Create a C+ program named ‘practscesxercise=t.cpp” ‘Add thematn fnetion and the appropriate include Hi), Copy the code fom the fle“practscetxerci seoutput -opb” ‘Modify the ode by adding an if statement after ea input item and ‘esting thatthe values input are valid 0. If theyre invalid then calcalation cant contin and an appropriate eror mortage should tbe cutput andthe program most terminate. The prsao-code below illustrates this. INPUT gross_sales IF gros eles > 0 TNPUT grost_expenses IF gros enpenses >= Detroit = ross. sales — gross expenses ‘Tak = ne_ profit * x, percontage (OUTPUT the abular rer here ELSE ‘OUTPUT “Can't coinue expenses can't be <0 ENDIF ELSE ‘OUTPUT “Cant contin sales can’t be <0 ENDIF 5. Compile and rum the program to ensure thatthe code is lopclly Solection - switch Statement ‘Another selection structure isthe avitch statement which implements multiple selection ase. The primary diffrence ketween anf statement and & auth statement i hat Sf sataments readily deal with ranges of valves whereas nuitch statements do No ‘Also, the expression isevahted to an integral vale such a: nt, cha, bool {ypes or the result of logiealexpesion, I(oue)Aas) (Create a file named “ewit.ch. cpp” and add the following code: lng namepnon 90a + Deine the mat faction Ad te following code to main: i , compile ane un the propre 2 Beton samen) 00) Notice thatthe second run ofthe program does not produce the dese result. This it besause the switch slaement werks by locating the appropriate case value, then exceaing all code fom tht poi’ until ether i encounters reak statement or the end ofthe oviten. Modify the switch statement tbe: Batar a manbes! (a00] (Case values can be of cha types. Comment out the caret code in min (to avoid unnecessary repetition during exeotion) and od the following code Sout SC vinta (a) oF () oF (0): % “8 Boeer (a) of @) oF (@)s fal | Geter (a) or @) oF) OB) otar (a) of (©) oF Ce): (2) [Notice onthe last un that there was no output. Often wien swish value snot one of the «cases a default case is given Modify the switch surement to ease ‘a1: cout << ch son mts Define the wa fietion Aad he following code to main: out << "he average Ae: " << total / 5.0 << endl: + Rocuve input for 5 values, add the value coe average then aout and pint the Comptia and rin the progr. tear a mers Ta) incer 2 mmbert (e6l Enter 2 camber: (071 Entec «pubes: (99) ‘This code does adequately perform the jo, however, the folowing code & repeated several times, Ifthe program was to average 100 numbers, for example, the code would soon become cambersome. In this ese, the code that is repeated ean be placed inside 8 repetition Structure. The £o= lop one sich struct. Modify man othe flowing code: ” out << tie average Ae! " << total / 5.0 << end “The thre stutements inside ofthe For loop (te [a This isthe initlizntion statement. Iti wed to initilize the wariable(?) coneling the loop. It is exceated once. ‘This the condition which controls the loop. If and then while 4 less than 5 the loop ‘will conve to erste. I sft executed fer the inialization semen, then again ‘reach update statement. = ‘This is the update condition. 11 is executed each time afler the code inside the loop Ener © member’ Ga) Enter s maber: (65) near 2 mmber: (09) The code is now more compact and achieves the same result. Also, should the program rnzed to be modified to find te average of 100 numbers, the change fo the program is ‘iia, Marly replace the code (total) / alae < wna 1 Ask the user for input forthe sumber of numbers to receive the input the ‘numbers then calculate and prin the average Te program now works for however many values the user nts. By coding this way the rogram remain un-bloated and is exible. It deals with 1 or |000 numbers and these the code remalns the same, ‘Programming Exercise: ‘Write a program to recelve Ninpat items from the wer and ‘alenlate the largest, smallest and average vale input. 1. Create a C++ program named “practiceBxezcicaror cpy™ 2 Add the main funtion ad the appropiate include ft) 3 Declare an int variable to hold the umber of vale obo input “4 Declare an int variable to hold he curent number ap, {Declare ait varable 6 Hoi the sum ofl als entered ‘ 7 5 8 ‘Declare an int variable to old the largest vl Declare an int arable told th smallest value pt Declare a oat variable to hold th average vale entered Ask the wer for and receive input for the mamber ems to enter, 10. Using a forloop teat N tne, ‘Receive input forthe current number, *Set the largest number by te following pseudo-ode TT carent number is rete than acest Tages = curent momber *Set the smallest umber bythe following peudo-2ode TR cureat numbur is smaller than smallest ‘smallest = cerret_sumber "Add he curent mune to the som 71 Caleuate ts average aumber by dividing the sum by he N (ou may ‘eed to use state -cat>0) 12 Outpt the values for largest, smallest and average. 13. Compile run the program to ensure thatthe code is logically Repetition - white Statement Anoter repetition strucare i the whe statement to will erate util «cain pe ‘efined condition becomes tac. ‘Crete a program named “whi Le.cop .epp” and ad the ellowing code: ‘Yinolude ] t + Define the main fneton ‘Add the following coe main: | cout << inter @ (-1 te fansan)? ste (oun t=) , "i 1 + eae, geting input and adding to snd prin the average 2 ntl the user ener 1 thx calelate This loop wil trate unt the wser enters the va the next statement immediately following the loop 2, upon which ine it wll proceed to ‘Compile and run the progres Geter a momber (20) Enter @ nober! (25) Enter s mbes! (20) Enter omer (21) Note: The fundamentals ofthe wns statement are similar 0 tha of the Eor statement and they can infact be used interchangeably. For example [LDec lara variable to contol the lop befor the mile lop. Teint i ~ 0. 2a. ce the contol conto inside the Lewnle (1 < 5) 3.Add he update statement atthe end ofthe fop, Le tey However, the general motive to choose a whi2e loop over & for loop is when the ‘umber of iterations of the loop is dependent upon somethire which happens inside of the oop Lo. The wer enters ava to nda termination ofthe loop. costae SSSSSSSSSSSS~*SY Programming Exercise: “Extend the previowsexerls to ase a whi Joop and rather than iterating times ser enters the valve 9999. oop Instead of for twill stop when the ‘Create C+ program sumed SprectdocBnorchouwnl erp ‘Add the main fanetion andthe appropriate incluce fe) Copy the code from "practScebxercisePor. ope” Medity the for loop to a while oop thst iterates unl the valu entered 1s 9999. Do ot ase the value9999 in the smallest, largest, “The rest ofthe code remains the same, (Output the resis CCompite and run the program to ensure thatthe code is logically Repetition-do white Statement ‘The third repetition structure isthe €o wh. loop. It behaves almost idenialy to the ‘este loop excep tht the code is lays executed before the condition tested Hence, the code wl always be exeuted atleast one tne st Define the main fetion ‘Add the following coe to mas ¢ Slceteee Sin! Sgnore ti09, \R") , " YP whise (tvaisatepat ) mun t= 2) “Se statioronstcdouble> (ested) / count <¢ en Tr Place the input insite a do-while loop that wl trate ithe input i iva oi the input does nt equal the sentinel value I’, which nates to terminate the loop. “The codes similar to tha in “ite. cpp*, however, ll the cde is “wrapped inside the do-hileatermen and dam validation is included. Coase he following cde: By Sinclear 7 Sin ignore (100, *\n") H | checks the input steam afer an input operation tose if thas filed duet invalid data being input for the required type. ie.‘ reseived for int. pe If this isthe ease he stream must be cleared of is bad” state and the charters in fhe input steam seared Se that further input operations can proceed, ‘Typically this code is put inside a do-while statement to conta geting input util the btn i valid, a oe (4 to santanns (23) Programming Exercise: “Extend the previous exercise o use do-while lop instead ofa ‘while oop. Input will top when the user enters the value 999 or ‘when tavald values are entered. An invalid value Ba valueless than 0. 1. Createa C+ progam mined “pract icebrorcisenohht ie. cpo" 2. Add the main fancon abd the appropriate include ile() 3. Copy the code fom “practtoatuered seni le.cpp 3 Declare an int variable to stor dhe umber of fvalid data tht bas boon entered and inilize it O. This vale shouldbe incremented ach time an invalid value has bees entered Modify the while loop to « doswile loop. The lop will terminate when the user enters 9999 OR when the user ont 5 invalid vals, Don't use te ald values or the value 9999 i he largest, smal, “Theres ofthe code emine the same, ‘Output the results Compile and run the program to ensue thatthe code is logically st User-Defined Functions AIC programs are constructed of one or more serdefine! functions of which one must be main. The programmer may also define addition! functions. The primary motive for implementing user-defined functions is to ensue that the progr i tly moduler. Thais, it consists of modules (fonctions) as tis considered. a, good programming practice to break the Inger programming task ito scveral smaller tasks Each ofthese tasks wil be defined within para function, ‘Another reason for implementing functions isto restrict the amount of duplicate code. For example, if «program receives several integer inputs, rater than having the bully ‘nde to validate input several tines throughout the program, on instance ean be plod inside function and that function canbe invoked several times Create program named “funcescaVok. cpp” anda the felowing code Toy ‘+ Define thea funtion, ‘There are vee components to wer define functions. Prototype The prototype is a declaration to the compiler tht finstion which has cern caaracterises (return type, same and parameters) edetined late The compiler needs be aware of the functions exisence bore encounters a function cl. The prototype i ‘ypically peed Before the main fineton. Le. Before any reference to the function ‘The thre distinct pars of function protalype ae 1. Returntype: The ype ofthe valve being returned bythe funtion, or the void type ifnone. 2. Function name: The funtion identifier. The sme naming rules apply a for Variable or eonstant identifier 3. Parameter lit: Zero oF more parameter (data) pased into the funtion, ‘The ist of parameters, i any, ae placed between the () Add the following code bufre mai: ss Don't forget the semi-colon *y/ at the and of the prototype: To: '+ Declare a function named cetctuaatahvennese() which has a ret type oF ‘youd and takes no parameters (eo da passed o funtion. Definition The funtion defiition contains the cade which willbe exeated each time the function is invoked (alle). The header ofthe definition looks the sme a the futon prottype, ‘Adtonally, the definition contains the block of code to be exceed which i contained within the (). Typically, the definition placed afer the wai nction, ‘Ad the following code fer mat: Sout co Minter canpersture An dagrose Calciue: © ‘cout << “in equal to." << ((0/5.0) © caleine + 22) "Se'* dogrecs abrambait a Te, + Define the function cetetusafabsenhest () [Notice te absence of "atthe en ofthe function header. Unlike the potty there {sno semi-colon ‘there as it would alter the meaning fom s fuetion definition 1 8 Function proeype Setar there will sot be any outpat ‘Curenty ther is no ouput as nas contin no exeeuble coe excep Eataea D9. In cer forthe code within the function to be exceed, te Rncton most be Foked Galle, call ‘The function cll isan instruction tothe compiler to iavoke the finetion and subsequently execute the code within te funtion defini, ‘Ad the following code to mas 56 ‘Call (invoke) the function celcsueatancenhest () Whenever the function cal, GaisiusZEaneeaneTe TT) is sncountred execution will hump to the funtion defntion and the conlaned code exeaed. When the end of the Tuntion i reached, the function exited and exevation sontines withthe next satement ster the function cll sear temperature in degrees owlciee’ 123) femal 22 13-4 dogreas Fancoahait, ‘The function cetciue2fahrenheit() can be cll any numberof times and fom within any user-defined function, Roturn Value {A funetion may retin a valve t the ciling fnction by way of the return statement. ‘The value retumed may be a variable (eg. Ear), » simple expression (eg. 0, 45 or ‘exue) ora complex expression (eg. 4.5 * 45 / ae. Recal that the an function hae a its ast statement ESTEE By This i the value that t returns to the operating system each time it fishes encoun. Main always retums & ‘ale * Other functions mayo may aot return a value, fa futon doesnot retum vale it mus sill declare a return pe, inthis ase, vote (Le. aching). \d the following fanetonprotypes before ease, Flost fanremaitaonieiva (7 + Declare the function fahresneLe2ceicius () ‘Add the following fanetion definition afer ma. 37 satorn ((5/9.0) * (fahe = 32)1; + Defias the fuetion tanrennes: tue) Ina non-void function, a retum statement must be given an only one valu cas be ‘returned, I isthe vale ofthe expression oc variable tht i tured. The type rewmed shouldbe the same asthe ype declared, however, the comple wil do type conversions ‘where possible “There are yeverl ways o se the value etumed fem a fuze, or example: Assign the valu to avaiable. Directly in an ouput statement as an operand, ‘Asa parameter to another function, ‘As pat acondtional expression A he following code to main: (Sout Seite oquel to sce cole 5 " fagrees Catotaa. <6 on + Calle function canrenhese2celesus() and assign the retumed valu to the ‘variable and ouput the resus, Vales returned bya function should bo used by the calling fnctionsccontingy. In his example the value retuned by the function, fahrenheit 2ceieiue() ie assened 10 ‘the variable cet and wed in the output statement. ‘Eater tonporsture in degrees Celcius? (23,86) Se"oqual 20 75-002 aageaee Pahreshor ‘Enter tenperatare in ogress Fahrenheit: (78.008) So'Squal 0 25-63 dogeess caleiwe, Parameters - Pass by Value ‘Generally, function whose tak ito perform some celeulstion an return the result wll ‘very often ot have input staremeat inside the feton elf Instead, the input wil be received elsewhere and passed tothe finetion. Aiteratively, the input may nok come fom user inp a al for example, he input may come frm 4 Se ss By passing the data to the function, it becomes more general and canbe wed by various code, The data received by a function upon invocation is elled parameter and can be any ballin or user-defined type A function may have vero or moe prametr. ere 0 _function protstypa,datinitton and call to Sfonctionsessoyva opp Modify the prototype fenrenneitaceietue() to the following + Declie the finction fanrenhese2celeswe() with one parameter of type “The name of parumetr can be omit inthe prototype or can dr from that inthe chi and char > cha [As you can se, the values ofthe two variables, char and chaca, main unaltered This is becuse the parameters are pared by value and any altration tothe vrible the funetion swap) do not affect the variables in main Evidently, chara and char2 ae te heve ther values swapped when the function rtums ‘To ensre that this does oocur the parameters shouldbe deficed as pa by reference. ‘Thais, ess to the parameter variable a reference tothe argument variable instead its value. Le the ares ofthe arguments assed. Thus, the patameter and the argument {ae in effet the some variable. For example Pass by Reference as ‘This achieved by using the adress 6) of opertorin the proype and deinton Mody he protorype to ‘+ Declare the inction ewe) with ow reference parameters. ‘The address (6) of operate is iserted afer the type and before the nme of each reference parameter. Modify the definition header eee Sd r 4+ Define the function eva 0 with tw reference parameters compile and fun the program, (ow the values of char and chara have been swapped a expected \d the Following code to main: o owe << Vaharis » ce vw rs | ine main 0 | ‘+ Define the man faetion The only difference between a ara of characters anda ctr thatthe lst character in the ering mst be the nll (\9) charter. This indieates the compile the end of the esting Declaration Add the following cove wo nase har eotel 50); Sher estza{se] = w+) + Declare three esting variables and assign iil value too ‘When assigning intl values during the declaration statement, the null character \o is automazcally appended to end ofthe e-ting Add the following code oma: Tr + Declare a estring variable without an explicit size with “thie iz cates” as When an amay (char or ote) is declare and the size isnot explcly stated the size willbe determined by the number of values assigned. Thus, the sizeof ct wll be the sizeof ("thie ie cetrd*) Le 13+ forthe nll characte: Output ‘The steam insertion (<<) operator canbe used to output esrngs. It works outputting ll charctr fom the beginning of th ray (e-strng) wl the \o i encountered, ‘Add the following code to main ——— ‘Prin the four ctringvasisbls ‘When outputting a e-rng only the name ofthe variable wse. i, te (are omited ‘he cutpet for este] will differ on your machine. [Notice that the last wo ering utp + As cate2 was inalised to“ no characters are oupt asthe frst element will contain the 3. + The output for este1 is odd and unpredictable, The sss with this opt that ccste1 is urintilized and as such, whatever values were nthe memory location previously ae being interpreted as characters and outed. I seems that @ \O character was by chance encountered in element 8 of t= Input ‘The steam extraction (>>) operator can be used to input into a esting variable with similar rules as apply fr other type input Le, The inti de-limted by white-space. ‘A the following code to ma a 1 ‘+ Recsve input into the two etrng variables (Once the characters have been extracted and stored inthe esting variables, the null character willbe appended tothe end of each esting. Conpite and run the peogeea. fete: gy fnere EI NAGS coe cae: cen tn ons ‘As inpt uring (->) ie de-timited by white-space, the dring “ehia i exacted and assigned 0 cotri and"1s" is asigned to anes," cate” remsns inthe input stream sd wl beth next data extracted, whitespace isto be included in the esting, the get ine() fimetion canbe used. Replace the code 5TH 55" GHEET] and ETA SCHEFT] with the fllowing: (in-geeline (oetel, sizeof (atei), Sn)? Sinlgetiine (oste2, amok (entra), Sn} The gettine() finction extras characters, including whitespace, from the input strat and sores chem nih gven coring variable Exracon vi stp when eter = 2 (eizeosicctst}) charter have been extmacted or te delimiter (\n) is encountered The delimiter will be exected fom the input seam and discarded and the null charter willbe appended tothe end ofthe e-tring. Inthis case, extraction wil contiue ui either 49 characters hae been extracted o the \n charater is encountered, The delimiter canbe any character although it every often the \n charter compile and sun the program SSeeets ay feat Enter a'value for cetel; (this 49 cots) 2 vale for oote2: (enta Manipulation ‘Te assignment operator (=) can only be wsed with estrngs during an initialization statment. In ode to aller the valu of cstring the c-sing fimztions ean be sed ‘Aad the following inetd statement before main: To, ‘+ Use the sting manipulation functions. Aad the following code to main: + Copy the sting “ext into cota, “The size of cotr1 remsns 50 but the vale snow be appended othe end ofthe eating. ‘The stze0t() function retuns the size ofthe c-string. That show many elements are inthe array. This does nr refer to the numberof valid haretersin the e-tng ‘There ate many c-string functions defined to manipulate e-sings, The fllowing ae the ‘most commonly used estring functions -te1\o". The nll character wil cerientes Retums the length of cets. ie, how many characters ar before the \o strut (overs, eee) | Appends cx ‘atrepy testes, cote2) | Copies cotca wo cated jeeronp fester, estea) | Compare eatra and cot? and etm the sifference. If they ae the sae, ois eared [Ad the olowing code to wa e

You might also like