You are on page 1of 44
2128/2020 (C+# Basies - C++ Programming Tutorial C++ Programming Language Basics ‘This chaptrexpins the features, technical details and sytaxesof the C++ programming language lssume that you could write some simp programs, Othenvise, ead "lnvodiction To C=+ Programming fr Novices and First-time Programmes” Tobe a proient programmer, you need to master two things () the syntax ofthe programming language, and (2 the creates ie, AB) associated with the anguage Introduction to C++ cee Standards c++ ie standardized a SO/EC 1482, Curent thare ae wo verso 1. +98 (SOWIE 14882-1998 Fist standard vesion of C++ 2. C+=08 (SO/EC 148822003 minor “bup-fa" to C==98 with no change tothe language, Commonly refer toa (Co98/C1 403 orFet Cr sandr. 3. C++ (ISO/IEC 148622011): Second standard version of C>+. Informally called C40, 98 it was expected to Fina in 200 but was no: released unt 2011. t adds some new features to the language; more sical it srestly extends the C++ standard lay and standard trp Ubary STL 4 C++14:Infomaly called Coty 4» sal ertenson to C+, wth bg ies and smal improvement 5. e+ informally aled Coa {6 C++ the net panned standard in 2020 Cos Features 1.Ce4 it. Cr+ supports aimost all the features of Like G Ce allows programmers to manage the memory Aecty 50 asto develop ecient programs. 2.C+¥ i 0. C++ enhances the procedua-oiented C language wih the object-oriented exenson. Te 0 extension facltates design, reuse and maintenance for complex software 5. Template Co. C++ introduces genetic programming, vis the so-alled tempate. You can apply the same Algoritmo diferent dats types 4.STL Ce provies huge st of reusable standard Ibrares, in particu, the Standard Template Library {ST +4 Strength and Pitfall +4 fs pomertl anguage for highperlorance spatcations inching wring operating systems and thei subsystems, games and animation C++ is alo a compler and sift programming language, wich is valy not meant for dummies For example, to effectively use the C++ Standard Template library (STL, you nee o understand these difelt concepts pointers, references, operator overloading and template, on top of the ebjec-tented programming concepts such ae classes ane objets. inheritance and pobmarphism an the radonal constace such 25 decison and lap. Cr+ is performance cent, The C++ compiler does nt lave wamingeror message for mary obvious programming mistakes, undefined and unspctied behaviors, such as ary index out of range, using an Unintzed vasble, ete due to the focus on pevtormance an eficency rather than the ease af we =i assumes that ‘tse who choose to program in C++ ae not dummies 2. Basic Syntaxes 2.1. Revision Below isa simple C++ program that ilustates the important programming constructs quent Row, while lop, ned {fele) and inpuvourpu. Read “troduction To C+ Programming for Novices and Fsttie Programmers I you need help in understanding this program. hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html TABLE OF CONTENTS (HIDE) 23 Statements and Blocks 24 White Spaces and For 25 Preprocessor Dvectves 4. Variables and Types 31 Veibler 32 Identifier 33 Vrisble Gechration 34 Constants fanst) 36 Assignment 2.7 Fundamantal Types 3 Lier for Fundamental Type: 4. Operations 43: Mixed-ype Operations 44 Overlow/nderFow 45 Compound Assignment Oper 46 nremenuDecement Opeat 47 Impl Type-Convesion vs 5. Flow Control 5.1 Sequential Flaw Contral 52 Conditional Decision. 53 Loop flow Conta 5.4 Interrupting Loop Flow - ore 55 Terminating Program 56 Nested Loops 5.7 Some sues in Flow Contra low ee 5. Cxecisee Wirking Corect and Good Progr 7. Stings 71 Sting Declaration and Inte 172 Sting npw/Output 73 Sting Operations 8, Formatting InpuvOutput using 81 Output Formating 83 Ererees 9, Reape 91 Array Decoration and Usage 93 Range-based for oop (C++11 94 Mult-Dimensional Array 95 Array of Characters» C-Sting 96 Gxercies 10, Functions 102 Using Functions 103 Defauk Arguments 104 Function Overloading 106 Pas-by-aluevs. Passby-Re 107 const Function Parameters 108 Pas-by-Reference vi "Refer 109 Mathematiest Functions Hee 1.10 Genering Radom Numb 1.17 bxereses 1. File Input/Output Header cfs 111 ramp Fle 10 112 evercees aa 21282020 (C+# Basies - C++ Programming Tutorial 12, Namespace 1 2% sun the odd and even runbers, respectively, fron 2 to 2 given vppersound 3 Also conpute the absolute difference 4 * (Gunoudtven-epa) G include —// Hooded +9 use 10 functions 7 Using namespace sta; ine maint) { 48 ne sunodd = @; // For accumulating odd numbers, inst to @ 31 int sunéven = 0; // For accumulating even nanvers, snst to ® 12 int upperdound;” // Sun front to this upperbound 13 ine abeDie#;// The absolute oitference between the tio suns 1 35/7 Prompt user for an upperbouné 16 cout ce "enter the upperbounet " 37 ein 95 upperbounds 18/1 Use-a while-2oop to repesteély add 1, 2, 3s.--» to the upperbound 21 while (number c= upperbound) { 2 ¢ (number © 2 == 8) {11 Even nunber 2 uneven += nunber; // Add number Lato suncven te pelse ¢ 11 08 ranner a sinodd += number; // Aad ronser into suntdd 2 Samunbers// Ancrenent unber 6y 2 38/1 Conpute the absolute difference between the two sums 31 (Sunoad > surever) { 2 absDif# = surodd = sunévens Bo pele g a ‘as01¢¢ = surEven = sunode BD 37 // Print she results 34 cout ce "The Sur of odd runbers 1s * ¢¢ sunbdd <& ends 39 cout ce "The Sur of even numbers 1s * cc suaEven << endl 42 cout ce "Ihe absolute difference ts "ce abs0S¢F ce endl; aD Enter the vppesbount 3000 ‘ne sum of 064 nonbers 1s 250900 “ne sum oF even murders is 250500 “he absolute difference Ss 508 Program Notes using nanespace std; ‘he names cout and endl belong tothe sta namespace. They canbe referenced vi uly quolfed name std::cout and std: :end, or simpy as cout and endl with "using nanespace ste” statement For snp, shall use the ter spprosch in this ection Il dieu the significance ber The return value of ndiests normal termination: wile non-ero typical 1} indicates abnormal termination. C++ compiler wil automaticly nse "return 103" athe end ofthe he main) funcion, thus statement can be omitted Instead of using numer value of zero and nonzero, you can abo use EXIT_SUCCESS or EXIT_FAILURE, which is defined inthe estat header ie, you need fortinclude nt maint) ¢ > 2.4 White Spaces and Formatting Source Codes White Spaces: Blot tb and newline ae cllectivly called wit spaces. Ce, tke most ofthe computing languages, ignores eta whitespace, Tha i ‘mulple contiguous white spaces are weated a single wht space Youneed to use s whitespace a separate two keywords or takes. 9 double average; // Need a white space between dovblle and average Aditionl woite spaces an entra linear, however, ignored Formatting Source Codes: As mentioned, extra white spaces are ignored and have ro computational signifcance. However, oroper indentation (with abs nd blanks and exta enpy tines greatly improves the readsilty of the program whichis extremely important for others (and yourself three days ter to understand your programs. Fr example, the following halle-wail works, but an you understand the program? include ciorsrean> sing noverpace rterint aaing)(eoutee file, worte*ccon return 83) [Braces Place the begining brace atthe end of the le, and align the ending brace with the stat ofthe statement Indentation: indent the body of a block by an era 3 (or# spaces, according ts level. For example tnt matn() {_// ace the begiening arace at the end of tye current Line BF Gaark 5 8) { U1 se 2ovel-3 blocs, Sndert nce out ce "You Pass” cc enely // sp level-2 block, sndent suice dese > hitps:iwwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 31a 2128/2020 (C+# Basies - C++ Programming Tutorial » "77 ending brace aligned wSth the start of the statenent MostiDEs (uch as CodeBlocks, Elise and NetBeans) have a command to reformat your source code automaticly Note: Traditional Cayo formting places the beginning an ending braces onthe sme colin For example sant matn() ‘ 16 (rark >= 50) 1) 9 Levelt block, Soden ence ‘ out << "You Passi ce endl; // An devel-2 block, indent cuice se ‘ cout ce "You Fat" ce anes > > 2.5 Preprocessor Directives C+ sourcecode is preprocessed before itis compiled nt object ode (a ite Editor orIDE_| step: Write Source Codes Source codes (.cpp), Headers (.h), Preprocessor _| Step 2: Preprocess~ Included files, replaced symbols compler | step3:compie + pu Object codes (.0b3, -obf Static Libraries (.1ib, .a)—___Linker__| Step Link Et tect Cole ee) Shared tbrais (411, .so)—r__Loader__| Sten Load T fun Input—ecPU__*) Step Fxecute output | preproesor directv, which begins with a# sign ucn 36 include, Adee} tl the preprocessor to perform a certain stan {such a ncuing » header ‘eo performing text eplcement,belore comping the souree code into objec cade, Preprocessor dectves ae not programing statements, and thereore should NOT be terminated witha semi-colon, For exam, Mofine PL 310359265 | //' To substinute the term PI nith 3.2858265 Sn ehs fle Inatmost ll ofthe C++ programs we ure include to ince the inptfoutpt steam Hbrary header int our program, 9.380 use the 10 Hrary ‘uncon to cary outinputfoutput operations (such as cin and cout More on preprocessor dietvs ltt 3. Variables and Types 3.1. Variables computer programs manipulte or proces dat. & vail is wad to store a piece of dota for processing. is alas variobe because you can change the vale More precise, a veriable is» named storage location, that stores 2 value of particular data type In other words, a variable has 9 name, ype and stores 3 velue + A-vaable has 3 name (or iden, 29, cadsus, area, age, height The name is needed to uniguely dently each vaisbl, so 3¢ to asign a vue so the arable eg, radiuse1.2,and revieve the value stored (ag, anea = radtustradiust3.1426), = Avaisble tse tps amples of type 6 «+ tne frionagers whole numbers such 5123 and -256; «+ double for loting-point ot eal numbers such 369.1636, $5.66 having a decimal point and lacbonal prt + A vrsbe can store a value ofthat prt type isimportant to tke note hat » variable in most programming languages i assisted with a ype. and can only store vale ofthe particular type. For example, 2 Ant variable cn store an integer value such 35123, bt NOT real number such a5 12.36, nor tees hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 41a 21282020 (C+# Basies - C++ Programming Tutorial such 5 *Hetlo* 1 The concept of type was introduced into the eal programming languages to smolty interpretation of data made up of Os and 1s. The ype determines the size andlayout of the data, tbe range of values, ad the set of operations hat an be applied ‘he folowing digram tustates two ‘ypes of variables: Ant and double. An int variable stores an integer (hole number A doubLe varisle stores 8 real umber. NAME VALUE TYPE unber 323 int sum a int ie i double D 3.186 |) avers = double ee | 55.65 |) Avariable has a name, stores a value ofthe declared tyoe 3.2 Identifiers - ‘nn dentifer is needed to name avaiable (or ay ater ently such as function ora class). C++ imposes the folowing rules on ident: An donors» sequence of characters of up to 9 eran length (complerslependen, ypally 255 character), comprising Uppercase an lowercase ters (2-2, AZ) gts (8-9), and underscore *_~ = Whitespace fli ta, neg) and other pec charac (sch +, 8.8 comms ele) ae not slowed. = Aa enter must begin with a eter or underscore It annot begin with a cgit Iemtifers beginning with an underscore are types reseed fr system ' Andante cannot bea resewed keyword ora reserved itera (ogint, double, if, else for lamers ar case-sensitive A cose ie NOT a Rose and is NOT ROSE. ‘Caution: Programmers dont se blank character in names. is ether not suppote, or wll pose you mote challenges Varlable Naming Convention 2 vats nama 3 noun 3 noun phrase made up of several words The fs word in lowerese whl the remaining words are intia-capitalzed, with no spaces between words For example, thefontSize, reomurber, ax, yin, xTopLeft and thisTstVeryLongvaribleNane. This convention also known as, come-cose Recommendations “Lttsimportant to dheose a name thats sel desriptive and clasly elects the meaning ofthe vale, €g,runberorStudents or nunstudent’s 2 Do not use meningless names ike 3B 3, 3,32, 399 3. Avo single-alphabet names, whichis easier to type but often meaningless unless they are common names ke x y2 for oorcinates i fone 4 iis precy otay tous lng names of says 30 characters to make sue thatthe name accustaly fle its meaning! 5. Use singly nc plural nouns prudent to iferentite Between singulr and pal varables For exam, you may use the warable roa to refer to single row numer andthe varabe rows to refer to many rows (such 25a aay of rows - tobe discussed ate, 3.3 Variable Declaration Tose» variable in your program, you need to fis ‘nraduce"itbydecoring its name nd yp, none ofthe owing syne 11 peclare a variable of » specified type type tdenesfiers nt optton; 1 declare multiple variables of the sane type, separated by comas type deneifier-1, faentifier-2, «ny tdentifier-ns oubte sun, stererence, product, quotient; (/'oeclare a variable an 25sigh a4 initial valve ‘ype identifier = volves nt magiewonber = 88; Hi declare multiple variables with initial values type Ldentipier-2 = volue-d, ..., tdentifier-n = value doubie sun = 0.0, product = 2.0 example average = (ark + nark2) / 2.8; // Use average, marki and mark2 Take note that: + Inve, younaed to declare the name ofa variable befreit can be urea hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html sia 21282020 (C+# Basies - C++ Programming Tutorial Cre ia “srongh-type" language. Avail takes on 3 type, Once the ype of» warble is declared it an ony store 2 valve belonging to this particle ‘ype, For example, an int variable can hold only intger such a 123, nd NOT fltng-point number suchas -2.17 or text eng such as "Mello". The concept of te was nroduce int the early programming languages to simply interpretation of data made up of Os and 1s: Knowing the fp of piece of data gees simplifies its interpretation and processing = Each warable an only be deetred ance = InC++, you cn delve avaiable anywhere inside the program as long as its declared before used, (nC pir to C39, al the vatobles must be decered at ‘he begining of function) Is commended that your decare variable ur efore i fit usd, + Tha ype of » aiable cannot be changed inside the program. CAUTION: Uninitialized Variabi When a varisle ie declared it contains gabsge until you aeign an inal vl, tempetant to tke nae hat C/C++ doesnot ee any watningferrr you se 3 varable befor nts = which ertany leads to sme unexpected resus For example, 1 rinclude 2 using namespace std; 4 tne main) 5 ane nansers 11 pectared but not initialized 5 cout ce number 11 No warningferror, BUY unexpected result 3.4 Constants (const) Constants are non-rodifabl verisble, daclared wth keyword const. Teirvales cannot be changed dung program execution, Ako, const must be intized luring dedlration. For examples const double PI = 3.195926; // od! to snittalize Jing Convention: Use uppercse words, joined with underscore, For example, MIN, VALUE, MXX_SIZE 3.5. Expressions Dm expression i combination of epertors (suchas sdlton “4°, subtaction*=",mulpleation **,dvsion°/") and operands variables 9 teal vale tht ‘an be evatoted oye a single value ofa erton type. For example, oubte principal, tntenestates prineisal * (11+ anteresthate) // evaluated to a douse vatve 3.6 Assignment An axigment storement 1. assignéalteral vl (of he RS toa vara (ofthe LHS}: 2 evahatesan expression fof the RHS) and assign the resutant ale toa variable ofthe LAS) ‘The RHS shall be a value; the LHS shal be a varible or memory adress) The syntax fr asignment statements: syntax Example /7 Assign the Literal value (of the AHS) to the variable (oF the UNS) Variable = Literot-votves omer = 885 11 Fvaluate the expression (RMS) and assign the result to the variable (LHS) variable = expression: sum = sum + unbers ‘The aesignment statement should be interotetd this way: The expression on the righhand-ide RAS) i frst evaluates to produce a resukant vale (led ‘ral or ight-kie}, Te alu then assigned othe variable onthe ethane (LS) (or hale which fetion that can hold 9a) Take note that you have to fst evaluate the RS, before assigning the resultant valu tothe LHS. For examples, ranber = 85 1 estgn Lazer value of & £9 the vorssble ranbor The symbol "= is known 35 the ssgnmenteperotor The meaning of “=” in programming i diferent fom Mathematics I denotes axsgnment iste of quai. The RHS ia eral valu; or an expression that evaluates toa value while the LHS mast be avarable. Note that x = X + 1 ial (an often used in programming, evaluates x + and assign the resultant ale tothe variable x x ~ x + 2 legal in Mathematics, While x + y = 2s allowed in Mathematics, its vain programming (because the LHS ofan asignent statement ust bes vaabe. Some programming languages use symbols, =>" af "= asthe assignment operator to avoid contusion wth equal 3.7. Fundamental Types hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html aia 21282020 (C+# Basies - C++ Programming Tutorial Integers: C++ supports these intager ype: char short, int, ong, ang Tong fn C+=11) in &nanvacressing order of sie, The actus size depend on the Implementation The integers except char) ate signed number (which en hel! zero, postive and negative numbers), You could use the keyword unsianed [char|short|inel1ongl long. long] to deca an unsigned integer which can hold zero nd postive number) There are 3 total 10 types of integers = _sgned unssgnee combined wit char [short|ine|Longl ong Long. ‘charactors: characters fog, '2",'Z' 0 9") ar encoded in ASCI int integers and kept in ype char For exam, character "8" i 48 (decimal 30H (hevadecimaly character ‘A 65 (decimal or 41H (hexadecimal character ‘a Is 97 (decimal or 61M (Mexadecima. Take note that the type char can be Interpreted as character in ASCII code, oF an 8-bit integer. Unlike nt 6& Long, whichis signed, char could be signed oF unsigned, depending on the Implementation You cn use signed char or unsigned char to expity cece signed or unsigned. char Floating-point Numbers: There are 2 fatng point types: float, double and Jong double, for sing, double an lang double pecson floating point umber. float and doubie are represented a+ speciied by IEE 754 standatd. A float can represent a number between 44.48220846%10°-45 and 133.40282347«28°38,spproximtes, A couble can presented 3 number between 24, 9406S64SK83246544510%-326 and #3, 79769312486231570x10°308, _pprosimated. Take note that nt all real numbers can be represented by float and deuble,oecaus thare ar infinite rel numbers. Most of the vals are approximates, Boolean Numbers: Aspecaltype called bool for boolean, which takes value of ether true o* false ‘The table below shows the pial ize init, maximum fr the itive ypes. Again take nae thatthe izes ave implementation dependent. category ype Description Cypieal Typical) (Typical) rocegers sn Sioned integer (of teas 1666) (2) -27eascea raeres087 (or sianed ine) unsigned ine Unsignedintage (of tesa 16) sae «asiserass ctor cwacer 2 {ca be ther sine or used depen on implementation) seed enor Carat Fp ying 2 “28 eo (guarantee to be sgned) unstgnes char Caractere iy integer 1 ° 255 (guarantee tobe unsigned) shore Short signed integer es 6s 2 ss rer (or short Soe) {or signee shore) (or siened shore tot) unsignes store Unsigned shot integer ff at ast 16585) 2 ° sas (or unstened shot fot) one Long signed integer oft at 32 bis) 4 (0) -2urearsan n2ere3067 (or tone ine) (or signed long) (or signee Long Soe) unsigned Lone Unsgnedong integer tt leas 32s s@ same ae bve (or unsizned Long Sot) ong ors Very lng sgn ager teas 64 is s 28 2 (or Tone Tore Sot) (or signed long long) (or signee Long lone int) (cons) unsigned Long Long Unsigned very long integer of stlesst Abs) 8 ° wa, (or unsignee lng long nt) (cous) feat oat Floating-point umber, =7 digs “ pateon 3.4038 inbers (E6754 angle recon fea pn orm) deute Double precionfoatng point number =15.igis 8 Lye 1.76308 AEE 78 double preciion fosting pi forms ong doubte Long Sole prcion fostng-pointrunber «19.12 (8) gts {EEE 754 quauple-precionMoatng pin forms) Boolean boot Beclean alu of ether treo alse 2 false (@) true (2 or imbers non-zero) wide chart Wide dbl) character 20 Characters charsé_t (Coa) charsz_t (C4412) In ation, many Cr library fanctions use a type called size_t, which is equivalent typede#) toa unsigned Ant, meant fr counting size or length with 9 and pos integers. The sizeof Operator C/C++ provides an unary stze0¢ operator to get the sz of the operand fa bytes) The following program uses sizeof operator te print the sze of the Aundamentl ype hitps:wwn3.ntu edu.sgihomelehchualprogrammingleppicpt_Basics.html a4 21282020 (C+# Basies - C++ Programming Tutorial 2+ Print Size of Fundanental Types (SizeofTypes. cpp) a+ 4 include 5 using nanespace stds a ne maing) { cout ce “sizeof(char) Ss." ce sizeof{char) << * bytes * ¢¢ endl; out ce “akzear{short) de "ce elzsor(enort) << " bytes "ce endl; 1 cout ce "sizzof{int) 35 "ce sizeot(ine) cc" bytes ” ¢¢ endl; M1 cout €e “sizeat(long) is * ¢e sizeof(long) <<” bytes * ce endl; 12 cout ce “Stzea¢{Long long) 1s * ce sizeot(Long tong) << * bytes” ce ends 13 cout ce "sizeof( Float) 1s * ce sizeof(Float) << ” bytes" ce endl 1k cut €e “StzeaF{deuble) Ss * ce stze0r{double) <<” bytes * ‘The e1snits header (gorted to C++ from Cs Limits.) contains information abot limits ofintegr type. For example Test Integer Linits in header * ‘include ostream Hinelude // snteger Lintte Using nanespace stds cout ce "Int ae = ce IMT_WWK ce ends 2 6 tne maing) { > out Ce "unsigned Ant max =" << LINT MOK << endl te cout ¢e "Tong Tong max = * << LLON6 HAK ce ends ML cut ce “Tong long nin = * £6 LLONG RIN << endl 12 cout ce Tunsigned long Jong max = "ce ULLONG,AAK <¢ endl 13 cout ce “its dn chars" ¢e GURATT ce endl Aa cout ee “char max =" << CHAR MAL ce endl; 15 cout ce Yehar min = 7 €e GAMRIN ce ond 1G cout €e “SSgned char max =" Header ‘The cctype heads (ported fom Cs etype-h) provides functions such as Lsalphat),Lsdigit(),Lsspuce(),Aspunct(), isalnun() isupper(),dstower) te determine the type of character: and toupper(), tolower() for ease conversion String Literals A String teas composed of zero of more characters surrounded by 2 poof double quotes, eg, “He1Te, word”, “The sum Ss *,**. For example String dtrectiontse = “Turn Right"; String greetingtsg = "elles Sing Merak may contains escape sequences. Insile a String, you need! to wee \" fr doublequote to ditingish it om the ending doble-quate, 9. \"quotee\" Single quot inside a String doesnot rquice escape sequence. For example, cout hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html oie 21282020 (C+# Basies - C++ Programming Tutorial Inan expesion bool vals an tras are converted to int Ofor fase and 1 or» non-zero value for true, Example (Literals) 1 /* Testing Prinitive Types (TestLiteral.cp9) */ 2 Rinclude 3 using namespace std; 5 tne main() ( © char gender = “rs 11 char 4s single-auotes 7 book fakarried = trues 11 Srue(non-zere) 0 Fa25@(0) 4 Unsigned short nunchilaren = 8) // (0, 255] 3 short yearorbicth = 29453" // (03767, 32768) se unsigned int salary = e800; // (0, 4294367295] 11 Govble weigne = 28.88; // with ¢raccional pat 32 loge gpa = 3.885 11 Nees suffix '#* For float 1417 “cout <<" can be used to print value of any type 35 cout ce "Gander Se * ce gender << endl; 16 cout ce "Ts married 42 " ce Married ¢¢ ends 17 cout €e "Ninber of children i " ce munchildren << endl; 48 cout ce "Year of Birth Le" ce yearorairth unmer of ehtleren Se 8 4. Operations 4.1 Arithmetic Operators (C++ supports the following arithmetic operators or number: short Ant, Long, lng Long, char (rested as Bi signed integer unsigned short, unsigned int, unsigned long, unsigned Tong Jong unsigned char, float, double and Long dovble, Operator Description Usage Exampl : Muhiplestion curt tem? 236 3a 1O +R Division ewet few 1/248; 1.8 /20+05 x Remainder (Modulis) expet Kew? SK 24a; SEDs + ‘dtion curt sem? = 1s 243 Ln eR2 waa subtraction ewe em? 2-2 aaa da A the sbove operators are binary operators, ie, they take two operand. The muliplistion dvsion and remainder take precedence over sedition ano subtraction, Within the sare precedence level fg, aon snl subtract he exotsson i evaluated frm let to right. For expe 243-8 evluted ((202)43)-4 Ieisimporant to take note that ant/int produces an dnt with he result wuncated 2, 1/2 + @ (instead of 85 Take note that C/C++ does nt have an exponent ower} operator "*" fe exciive-or, not exponent) 1+2a Atb+e)(S-d-e) (7 pe tient 6a a rst be writen a5 (162%3)/3 + (4*(b4¢)*(S-d-8))/ - 6*(7/gHh). You canat omit the mukipaton symbol" (sin Masham, Like Mathemstis, the muti Parentheses () have higher precedence, The operators and ion "1" and divsion °° take precedence ovr adsition °+* and subvaction eleasscitve. hati, + 2+ 3 + Als weated as (((142) + 3) + 4). 4,3 Mixed-Type Operations. If both the operands of an arithmetic operation belong to the same type, the operason is cared out in that ype, and the result belongs to that type. For cramp, iat/int + int; double/double » double, However, tthe we operands belong to diferent pes the compiler promotes the value ofthe smaller type tothe larger type (enown as impli type casing. The operation is then cai out in the orger ype For example int/double + double/double + double, Hence, 1/2 » 8, 1.0/2.8 » 0.5, 1.0/2 + 0.5, 12.0 + 8.5. hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html as 21282020 (C+# Basies - C++ Programming Tutorial For example oe beams Operation ata int 2.4 int 3 4 ant § doule 2.23.3. double 2.2 + double 2.2 + dovble 5.5 mix 23 int 2 + double 3.3 + double 2.0 + double 3.3 + double 5.3 ae ay Ane 1 / ane 2+ ant @ double 1.0/2.8 double 2.0 / double 2.0 + double 0.5 mx 1/208 int 1 / double 2.9 + double 1.8 + dovble 2.0 + double 8.5 Example 1 /* Testing wix-type anithnetie operations (Testhixtypeop. cpp) */ include ‘include clonanip> _ // neeced for formatting Aloating-potnt nombers Using namespace std; unt id= 2, 2-4 cowle 1 = 2.5, 62 = 5. 3 6 tne main 12 // Print #toating-points in fixed format with 2 decinal place 11 cout ce Fixed ce setprecssion(2); // need cionanin> 12 cout ge SN Ge ce AR GEN ge M02 ce ones // 6 Me cout ce dd ceo Tce gD de TET ce Led? Ce endl // 7.5 $5 cout ce AD ce a ced Ge TE Ce Mad? Ce endl // 7.8 BP cout ce 11 ce Tce Bc Te ce HD ce als) 2 a cout ce gd ce Tee aR eT Ce LD ce eels // 2.5 3B cout ce AT ce 7 ce ce TT ce M18? Ce Me]; /) 3.0 Gon Do cout ee A ce TT ce ee Te ce IND ce ends // 8 22 cout ce dd ce 7 ee a2 de TE Ce ded? ce endl // 12.5 2 cqut ee ce ced Ge TE" Ce MND Ce endl} // 30.8 24 2S cout cc ce fo ce ee Te ce L/D ce ents) 8 2s SPN E YC alae Ce end; // 0.5 2 Spo ean cet at ce $1782 ce endl; // 04 a) 4.4 Overflow/UnderFlow Study the ouput of he following program: U* rest aricmetic Overflow/Underflow (Testoverflow.cpp) */ Using nanespace stds 1 Sint ming) { 6 // Range of int is [-2147483648, 2147483647] Soe tLe 7147683687; 1 moe Se cout ce 11+ 1 ce endl; // “250748648 (overflow) 3 cout ce iL 4 2 ce endl // -247883647 32 ine 42 -rrareanees; —// nin Soe BB cout cc AP 1 ce erly // 2247403647 (undertow) 1a cout ce 42 = 2 ce endl; // 247A836N6 BS cout ce 12 Az ceendls 1/0 vy In atametic operations the resutant vale Wraps around i t exceeds ts range fa, overow or underflow). C++ runtime dees not issue an erorivaming message but produces incorrect result Itisimportant to take note that checlang of overfow/underow isthe programmer's responsibly, e, yout ob! ‘This feature isa legacy design where prcestors were slow. Checking for everflow/undetow consumes computation power and reduces performance Te check or artnet ovelow fron 35 Secure cdg) is ecus, Google or INTS2-C Ensue that operations on signed integers do not rsutin overtow® inn securcoding cerry 4,5 Compound Assignment Operators ‘Besides the usual single assignment operator "=" cesebed asl, Ce» also provides the so-called compound atignment operators a tee: Operator Usage Description Example - var = expr Assign the value of the LHS to the variable at the RNS. x = 53 . var ¢= expr sane as vor = vor + expr 425; sane as x hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 21a 21282020 (C+# Basies - C++ Programming Tutorial Operator Usage Description Example var -= expe sane as var = var ~ expr xoe 5; sane as ees var *+ expr sane as vor = vor * expr xte 55 same as xn xs bf var /= expe sane as var = vor / expr x fey cane a x= KS x var X- expr sane as vor = vor % expr 1% 5; sone ase = ES 4.6 Increment/Decrement Operators C++ supports these unary athmetic operators incemant “ss and decrement xis oe Increment by same asx == 1 * Decrement by 1, samea5x-= 1 For example, 1% Test on ncrenent (+4) ane decrement ( ‘include clostream> ) Operator (Testtncoec.cop) */ ant mark = 76; 11 dectare & assign 5 tne main 7 cour ee mark ce endl; // 76 a ares 11 tncrease by 1 (post-increnent) re cout 6 using nanespace std | tre main() ( 3 ane 4 se cauble a u 42/7 print Floating point nunber in fixed forrat ith 4 decinal place 13 cout 5 inetude 5 sing namespace Sta > soe mang) ane sam = 63 38 couble averages AL for (lat number = 25 qunber <= 180; tHnunber) ( 2 sume nunber; |" / Final sun 15 ine 5058 po) M4 average = sum / 100; // won't work (average = 58.8 instead of 52.5) 15 cout ee Fixed £6 setprecistion(t); 16 cut ce "Average £5." Using namespace sta; 1] Print floating-point nuaber in fixed forwat with 2 decimal place 6 tne main 3 cout ce faxed ce setprecsston(3); 12 // Test explicit type casting no teins a, 2-8 a2 cout ce 1) 12 ce eres we 13 cout &e (Gouble)31 12 €e endl; // 0.5 3& cout ee 12 J (doubleys2 ce eral; // 805 35 cout ex (double) 42 / 42) <¢ endl // 0.9 VP double dt = 5.5, 2 = 6.6; ae caut ce Canty / a2 ce ened 19 cout ce Cinta / 12) cerenely 17 21/7 Test snplict type casting 2 aon; 11 int toplicitly casts to double 23 cout ce at ce ently // 49 wm a as 41 double truncates to Ant! (karning?) Converting between Celsius and Fohreshelt: (ConvertTenpersture. cpp) + celsius = (5/9)(Fabrenhett-32) + Faprenneit = (9/s)celsius+s2 2 6 include 7 include clonanip> _// needed for formatting floating-point nombers | Using namespace stds 2 18 int ming) { a1" buble celstus, fabrenhest; 2 12 // Format Fleating-points in fixed with 2 decinat places 14 cout ce #hxad ce setprecision(2); 6 1S cout celsius: Ae fahrenheit = celsiust9/S + 32; 19/7 s/stcelsius + 32 gives wrong answer! iy? 28 cour ce celsius ce "Ess * ce fonrennest ce °F ce ends 22 cout ce “enter the temperature in fahrenheit: "y 23 cin 95 fanrennests 24 celsius = (Fahrenheit ~ 3295/93 25/7 5/9*(fanrenneit = 32) gives wrong answer! uty? 26 cout ce Fahrenheit ce “F fs" ce celsius °C ce endl; ay operator staticecastetype> C+ introduces anew operator called static_cast to perform type conversion (because th regular cat mentoned eaters too lox and could produce expactd refute, state_cast sgn n ear if conversion fle. For example, Ene 1 = static castetnt(@); float # + seatde-castcflos-(0s ang 2 = static cestclogr(@)s 4,8 Relational and Logical Operaters ‘very ofan, yu need to compare two values before deciding on the action to be taken if marks mor than or equal to $0, print "PASS! ‘C+ prides sx comparison operator fr relational operetos Operator Description Usage Example (x5, =8) - quate exprt = expr2 (eo + false ' Not Equal to exprt te expr? (ty) + tre > ester than exprt > expr2 (> 9) + false » restr thin or equalto exert >= expr? (>= 5) + true < Less than loxprt < expr (8) + false < Lessthan or equate exprt >= exer eB sire In cv4, thee comparizon operation retums s bool vale of either false or true (tor non-erovake) hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 15104 21282020 (C+# Basies - C++ Programming Tutorial Exch comparizon operation involves two operands 9, x <= 109.1 i iva to wrte 1 < x € 168 n programming, Insese you need to oresk out the So comparson operations x > 1, < 188, anin with wih logical AND operator. ie, (x > 1) && (x € 108), here && denotes AND operator. (C++ provides fou ogeal operators which apeate an Boouean aperands on operator Description usage a Legit AND expt ak exer2 " Logit on exert || expr? ' Legial NOT leer . Logial xO expert * expe? ‘The ruth tabs ae as fotows: ano we false false false false on ()|) tre fats hor (tue false fase true wor (+) trae falsa false true false 1) Return trut if is betwen @ ond 188 (inclusive) (eds ay a8 (ee a0) 11 Return true if «8 outside @ and 300 (inclusive) (gear 4) 68 (year % 300 I= 6)) [| (year X 400 =) a Exercise: Given the year, month (112), and day (1-3, ite a ealean expression which retums Wue for dates before October 15, 1582 (Gregorian ealndar cent over dat ‘ans: (year < 4582) || (year = 1582 68 month < 10) || (year == 1582 48 nonth == £0 88 aay < 15) 5. Flow Control ‘Thave are tree basic fw conto constructs - sequent, canditana (or dein), and loop (orien, a htt below Sequential Conditional (Decision) Lo0p (Iteration) 5.1 Sequential Flow Control 1 program if» sequence af instructions, Sequential flow isthe most common and straightforward, where programming satements are execute inthe order, ‘hat they ate witen- fom top to otto in a sequent mannet nal (Dei n) Flow Control ‘here ae few ypes ef condtonals, then, there, nested Wesel.) siteh-case, and condtionl expression syntax Example Flowchart 11 Ashen 86 (mark 9» 50) 6 hitps:iwwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 6104 2128/2020 16 ( booteantxpression ) ( > 11 Af-then-else 46 C booteantxpression ) { trve-block dese ¢ "false-block 3 > A Cbooteantxpr-1 ) ¢ blocked 5 } else 4F ( booteantxpr-2 9 block-2 3 } else iF ( booteantxpr-3 ) lock=3 3 } else iF ( booteanexpr-s ) y else ( ‘etseBLock 5 » switen ( selector ) ( tock-15 break; cae vatue-22 lack-2; breaks case values ‘btock-3; breaks ae vatue-n default: ° defoult- block; (C+# Basies - C++ Programming Tutorial cout &< "Congratulation!" << endl; out ce "keep St up” > 50) ¢ cout ce *Congratulation!™ << endl; out c "Heep it upi” << endl yelse ¢ cout ce "Tey Harder! << end; ) iF (mark = 90) ¢ ) else 1 (park 90 7 else 14 (park 9-50) ( cout ce"C" ce ends else 1+ (ane 9» 50) ( cout << "D" ce endl, pele ¢ « ) char oper Lat mura, aun2, result; BULA (oper) { result = nun + nun2s breaks result = muna unas breaks esult = mum * nunz; breaks cose 7 esult = muni / nant; breaks cefault out ce “Unknown operator” << endl; t ‘booteenrest>£ — —> blocks f V T break, voluez? -—> block2 5) Tr break, 4 blocks |P2**5} fF + defoutBiock break, ® “snith-case” gan akaratve to the “nested In a sch case statement, a break statements needed foreach of the cases, Mere is missing, execution wil ‘tow rug the folowing ese You cn ue ether an Stor char variable a the case-selctor Conditional Operator: A conditional operator i 3 tematy B-operand operator inthe form of BooLeonéxpr ? truetxpr the booleantixpr, exakistes and returns the vale of truebxpr oF folsebxpr {FalseExpr, Depending on boateenExpr ? trueBepr + folsetnor cout ¢< (rark >= 58)? “PASS" : “FAIL” 6¢ ends mac = (> 8) 2 a:b; // RUS returns a or 8 Bos = (29a) Pas as // RIS returns ao Braces: You could amit the braces { ), tate is only ene statement inde the block For example ¢ (mark >= 50) cise ¢ ” out ce SFATLY ce es out €e "Ty wander! << endl , ‘han ore statenents, meee ( Howaver |tecommend that you keep the braces, eventhough there only one statement the Bleck to improve the readily of your program. hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html Tia 21282020 «1000 5.3 Loop Flow Control ‘ain, there are fen types flops: forloap,whiledo, nd do-whil syntax Example 11 for-to0p 11 Son from 1 t0 2000 for (nse; tests post-proc) (int sum = 8 body 3 for (ine mune ? sun be numbers > 11 wntte-do ne sum = @, number vintte (condition ) € shite (uber 1000) { yo Hrurteri ) 11 dosmite int sum > @, number at ot ody 5 sun numbers > sina nite (condition ) 5 >) while (nunmer <= 1088); (C+# Basies - C++ Programming Tutorial runber <= 1088; number) ( Flowchart Fett loop) = test "body | F (exit loop) “rt F (exit loop) ‘he ference between while-do ant d-while les inthe exe ofthe body and cndton In whe-d, the condition is tested fst The body wl be execute if the onion sre and the process repeats. In do whl, tre bodys executed and then the contin is tested, Take not that the body of doh wil be executed Atleast ance. possbly zea for whle- do ‘suppose that your program prompts user fra umber between 1 ao 4 (numer 9-2 AR runber <= 28) vata = trees white (Ivalid);—// Neos 9 saniecolon to torninate docile Below isan example of sing while de: sine’ Cganeover) ¢ > nd checks fr vad input do-while wth a boolean fg could be mare approprate Example (Counter-Controlled Loop): Prompt user for an unperbound, Sum the intger from It. given upparbound ane comput its average. * sun from 1 to a given upperbound and compute their average (Sinturbers. cop) 3 4 include 5 using manespace stds a ne maing) tnt sum = @; —// Store the accumulated sun 9 int upperbound; 18 cout ce "Enter the upperbound: “s hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 61a 21282020 (C+# Basies - C++ Programming Tutorial 11 tn >> upperbounds 13/1 Sin from 1 to the upperbound 14 for Cine nunber = 15 number < woperbound; ssnunber) { ra) : 37 cout ce "Sum 15 * ce sum ce endl; 18 Gout ce "average 45." Example (Sentinel-Contrelled Loop): Promet ser fr postive Integers, an elpay the coun maximum, miimum and average. emirate when usr 2 | nintmun and average. Terminate the input uith -1 (StatNuabers.co9) */ 3 include ciortceam> 4 include _// for setprectston(n) 4B ine main0) ¢ 3 Ene ninbertn; // Snput number (positive snteger) xe ine counts @;—// count of inputs, ‘init to 8 31 ine son= 6; / sun of inputs, init to 8 32 int max =; ——_// max of inputs, Init to nininun 13° ine min = INTRAKG // nin of inputs, init to naxsnum (neee ) 36 1 Read Inputs until sentinel encountered 17 cout ee “Enter a positive integer or ” ce sentinel << * to ext: “5 18 while (cin >> numberin 8 ober I~ sentinel) { 8 71 Shock input for positive integer 2 4 (wumberin > 0) ( z um te nunberns B | (ax ¢ nunbertn) aax = ourdertn; a A€ (min > nunbertn) ain = ronderrns B pete d 35 ‘cout cc Terror: Snput must be positive! try again...” <¢ endl p > a out ce “Enter a positive integer or * ce sentinel ce" to exit: *: » 3 3 cout ce endl; 34 EF (count > 8) ( % cout ) = cout header. The sexprecision() sticky. That is, will ‘eisin in efect unl anathar value et. Exercises «000 5.4 Interrupting Loop Flow - “break” and continue ‘The brea statement breaks out anc es he caren Ganermo 199, hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 91a 21282020 (C+# Basies - C++ Programming Tutorial ‘The contsnue statement sborts the curent eration and continue tothe netiteaton ofthe curantGonermost lo, braak and continue ae poor structures as they are hard to ead and hard to follow. Use them only if absolutely acess. You can slays ita the same rogram without using break and continue Example (break): The flloing program its the non-prime numbers between 2 and an upperooun. 16 2 |* List non-prine fron 1 to an upperbound (NonPrineList cpp) 4 include 5 Rinetude 6 using nanespace std > soe masng) { ant pperdound: 3e cout ce "Enter the upperbourd: 12 for Cint number = 2 number <» vpperbound;.ssmumber) { 2 11 Not a prise, i¢ there tas factor between 2 and sqrt(oumber) ue ne maxFactor © (int)sore(nuawer); 15 for (int factor = 2; factor ce naxtactor; +sfactor) ( 46 A# (runber % factor == 8) {0 // Factor? y cout << nunber <<" "; a breaks // & factor found, no need to search for more factors 2 > 2 ? a} 22 cout << endl; 23 return 03 2} Lees reaite the above program to lis al he primes instead A boolean fg called 1sPrine is used to indcate whether the curent nue 2 prim. es then eed to cone the printing ar 2+ List prines fron 2 to an upperbound (PrineListatthareak.cpp) 4 include 5 Rinelude © using nanespace std ne matng) { 9" Ant eppersound; 38 cout ce "Enter the upperbound: *; 11 Cin >> upperounds 12 for (int number = 25 nunber 5 Rinelude 6 sing nanespace sta; a int. main) { ant pperdound: 38 cout ce "enter the Upperbouna: M1 ein 95 upperbounds 13 for (int number = 25 nunber <= uaperbound; esnunber) { u 1/ Not prina, if there is a factor betwean 2 and sit of nunbes 6 fine maxFactor = (3nt)sere(nuneer); 16 bool fsPrine = trues v nt factor 1 ile (sirine Wh factor c= maxFactor) ( 3 4 (number X factor == 0) {// Factor of nunber? 2 ‘eprine » false a } 2 ? hitps:iwwn3.ntu edu.sgihomelehchualprogrammingleppicpt_Basics.html 2oiaa 21282020 (C+# Basies - C++ Programming Tutorial 2 46 (serine) cout 28) ( out ce "too wary errors <& eh nse (21)51/ Terninee he program 1) on shorts, ) The “return” Statement: You could alo use» “return returnvalue” statement inthe ain function ta terminate the program and return control back to the Operating System For example, nt main() ¢ IF Gerrorcoune > 28) ( out << "too ary eevors” <¢ end; Feturn -15// Teoriate and return control to 0§ fron nang , 5.6 Nested Loops - ‘The flowing lagram ilastates a nested forJoop ie, an inne! frleap within an outer frleap, hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html ria 21282020 (C+# Basies - C++ Programming Tutorial I intialization Oy tue — ‘Outer-loop's body = Inner Loop test S54. initiatzation al false tue test >) body Le post-processing false post processing Next Statement Tryout the following program which pins» &by-8 checker box pattem using nested oops, 6 flows. 1 2 "© Print square pattern (PrintSquarePattern.cpp). ay 4 include 5 Using namespace sta > fine maing) 9 for (int row = 25 row . sl, 3 7 6 v > ° ‘This program contains te nested for-oops The inner loop is wed to print «row of eight ® % which soloed by printing 8 nealing. The outa loop rapeste the inner oo te pit ll the ows ‘suppose that you want opin this pattem instead (in program called PrintcheckerPattern. pp ‘You need to print an acdonal pce for even-number rows You could do so by adding the following statement before Line 8 5¢ ((r0u X 2) = 6) (—// print a Deading space For evan-nubered rows Exercises 1 Print these patterns using sizes You shoul! use as few printing statements a possi ted loop in 3 program call PrintPatterntx) Use a varabl called size fr the size ofthe pater and try out vous Peers sat Pee esasan 223456 e ” © © © hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html aia 21282020 (C+# Basies - C++ Programming Tutorial The equations for msjr and opposite diagonals ae ow = col and row + co = sca «1, Decide on what to print above and below the diagonal 2 Print the timetable of 1 to 9,3 follows, sng nase oop. Hints you need to use an fle statement to chack whether the producti ingle oF oxble-ig and int an sedonal space if needed} 3. Pie these patterns using nested bop. o ms © © 5.7. Some Issues in Flow Control Dangling else: The “angling ese proslem canbe israted 35 flows: Ge) WG-0) ‘The alse aut inthe above code is syntactical apelcable to both the outers andthe ier. The C++ compiler says aszocte the else cause withthe Innermest if the nearest if. Dangling else can be vesoed by spphing expt parentheses. The above codes ate logical incorct and requ expt parentheses as shown blow Cae 16 == 8) cout cc “ane 4 are zero" «ends delse cout << "4 18 no aero" ce endl // ron-ambiguous for ovter-i¢ ) Endless Loop: Te following constructs tte (te) Coed is commonly used i seems to bean endless loop fr infiste lop, but i usually terminated via a break ar return ststement inside th lop body. This ind of codes hard to red - voi if possible by resaring the conition 5.8 Exercises \r000), 6. Writing Correct and Good Programs Its important to wite programs that produce the crrect resus. Ris also important to wite progtams that ates and you yourself tee day ate) can raetand, sth the programs an be maintain al these programs 9008 pogroms Here are the suggestions: + Folow established conventions that everyone has the same bass of understanding Format and layout ofthe source code with sporopite indents, white spaces and white Ines. Use 3 oF 4 spaces for indent, nd blank lines to separate secions of code. choose good names that te sel-dasrtive and mesningfl eg. row. co, size, stax nunstudents. Do not use meaningless namts, such a5 8, & ‘oid sngealphabet nares east type but often meaningless), except common names thes y, 2 for co-ordinates and fr ndex Provide comments to explain the important ae wel a alent concepts Comment your codes liberal te your program documentation while writing your programs ‘eid un-stractred constructs such 2s break and continu, which are hart fllow = Use ‘mono-space! fonts suc as Consla, Courar New Cour for wing/splaying our program Programming Errors ‘There are ganrally tree dasss of programming errs: 1. Compilation Err (or Syntax te an be fed easly 2. unt Ear, progam hale prematurely without producing the reuts can algo be fined say. 4 gil rar: program completes bu produces incorrect rests, teary to tec ifthe program slays produces wrong asl tis extemal har to ft ifthe program produces the comet result mat ofthe tines, but incorec result somtimes For exam, 46 (rare > 58) : out ce PPASS” ce end delve ( hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 23104 2128/2020 (C+# Basies - C++ Programming Tutorial cout <& “FAIL” €¢ eas , This kind of eros i very serous ifs net caught before production. Wing good programs helps in minimizing and detecting these ers. A good testing strategy is needed to ascertain the correctness of he program. Software testing isan advanced topics which i beyond our current scope Debugging Programs Here ar the common debugging techniques 1. Stave atthe screen! Unforunately, eros usally won’ pop-up even if you stare at it extremely hard 2 Study the enor messages! Do not close he console when err occurs and pretending that eveything i fine. This helps most of he times. 2. Inger rit statements at appropri locations to disply the intermediate ests, Kt works for simple tay program, bu it i nether flecve nar efile for complex program, 4. Use » graphic debugger. Tiss the most effective means Trace program execution step-by-step and watch the valve of arable and outputs 5. Advanced took such 35 prof (ngaded fr checking memory leak and function usage, {6 Proper program testing to wine out the logical errors. Testing Your Program for Correctness ow to enaure that your program always produces comet result, 100% ofthe times? Ii impossible to uy out al the possible outcomes, even fra sme rogram. Program testing usually nvoWes 2st of representative test cases, which are designed to atch the major css of eros. Program testing i beyond scope ol his wing, 7. Strings Cre supports two types of sings: the orginal Cte sing: A sting is 3 char aay, terminated wit) a NULL character "\@" (Hox tials called Character Sting oF C-syl sting. Cstrng wil be cused ate 2 thenaw string css introduced in +198, ‘the “high-level string cles le recommended, because it fe much ester to use and understood. However, many IAghey programs used C-vings: many programmers ls use TowlevelC-stings for contol and efficency,fushermese, in some stusion such a command-line siguments, nly C-stvings ate suppered, Hence, you may have to understand both ses of strings Howaver,aoidC.sting uns itis absolutely necesay Wo sl describe string dss hee, and C-ng ltr 7.1. String Declaration and Initialization Tose the string since the cstring> header an “using ranespace ste ‘ou can declare andl) initlze » sting wth a sving eral ints oan empty string, or (@ inital wth another string object. Fr example, string stra(Ciellot);/ Ineialize with a string Literal (Inplieit nstalszation) String stra= "wordy // Inieialiae with a string Literal (Explicit snitlalseation via assigonent operator String S34 1 Initialize to an eoty string String Strd(stety;_// Initialize by copying #Fom an existing string object 7.2 String Input/Output For example, 1 /* Testing steing class input and output (TeststeingtO.cpp) */ 2 include 4 include 5 Using namespace std; // Also needed for csteing> 7 ane ming) 3 string message("Hetio")5 9 cout ce massage << endly M1 // Input a word (delimited by space) into a steing 42 cout ce “Enter a nessage (no space)!" 3B din >> nestages 14 cout ce message << endl 1G cinvignora(nuneric_tinitsestreamsize>s:nax(), °\n")s v 7 Flush cin up to neuLine (need header} 18 39 // Input a Line into a string 28 cout ce "Enter a nessage (with spaces): “; 21 geeline(ein, ressage)s.// Road input fron cin into nessaee 22 Gout ce nestage ce endl; hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html aia 21282020 (C+# Basies - C++ Programming Tutorial Notes: = We needto"Binclude " tous the string cas, and "using namespace sta" ab string i datined under sté namespace n >> aS tr" ead word (dele by space fom cin feyboard, and assigns to string variable ast, = getline(ein, astr) sth entre line opto "Vn" rom cin and asgns toast The "\n" characteris discarded, 1 To fush ci, you could use ignore nunertc_Lintts:: Inthe cLintte header sk), "\n') function to dcr athe characters up to *\o! nunerie_Liakts ie 7.3 String Operations Checking the eng of string sot 2ength(: nt sizes Siting str(elle, works); cout te serlengen() ce ena; // 32 cout ce strcsize() ce ely (22 Cheek for empty sting book enpty()s string stra(elto, worte"): cout ce serhcenpty() c€ enels// 0 iaise), cout <6 Strdersty() ce eel; 12 (078) + Copying ftom anther sing: Simply use the assignment) operator. string stracelie, wente"y, stra = Concatenates with nether sing: Use the pls (+) operator, af compound pls (+=) operator sering stra(*tetio,"); ring seF2(0 mre"): Read Wte individual character of tring chard st(Ane index): D ndening (subseriot) operator, #9 Jndex Bound check string str(elle, wore") cout ce streat(@) ce endl; // cout ce seria] ee erly coat ce sereat(strelength() "1) 6 eral // streat(a) = fats // este to index 2 stele] = ows = Sxrctingsubsting string subste(int begiatndex, tat ste); Return the substring stating at begintndes, of stze string str(elle, worte’); cout te seresubste(2, 6) candy // “lo, = Comparing with anther sing nt conpare(string another): ‘anpare the contevt of ths string with the glven another. Natuen @ Uf equols; o negative vaive 1¢ this string 1s Leis than another; positive value otheruse a= ond t= operators Ceapare the contents of two strings hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 25104 21282020 (C+# Basies - C++ Programming Tutorial string stra(“Hel2o"), str2(alle"), stra(*helIo"), stra(el2e"): cout te serdcompare(stea) ce end; d's 3a cout ce strdconpare(sted) ce endty fH cout ce serdccomparelsted) ce eral // 6 ‘tr2) cout <€ “Sane” Ces SF (Gtrs fo stra) cout ce “Dutrerent™ ce etd: out <6 boolalpne;// print bool as teue/ false oat ce (Stra fe stra) ce endl Coat ce (Sted = stra) & endl «= Seare/Replcing characters You ean se the functions waiable inthe calgoritha> suchas replace), For example inctuce calgorstam> ring strCielle, works); replacecstrbegin(d, str-eed()y "1, cout ce str ceed; i eo, wird = Many ote. Example 1 17% fample on Coe string function (Teststringop. cpp) */ include ‘include estring>// use string class Using manespace sta; string neg = "hello, wordé!"; 3 6 ine main ¢ 3 cout ce msg ce ends 3 cout ce msg-tengtn() << endl; // Length of steing xe cout ce msglat(l} << endl; // char 3¢ index 1 1 cout Ce magi] <& only 11 sae 35 040 12 cout cc msguerpty() €c endl; // test or enpty steing 13 cout ce msg.substr(3, 3) << endl; // sub-strang begins =t Pra I pos dof size 3 15 cout €e asgereplace(s, 3, *aty") ce andl; // replace sub-st 16 cout €e wsg.append"end") <¢ ena 11 append behing 17 cout ce mag 4 vend” €€ endl; 11 same as above 1 cout €e msgeinsert(3, "Insert") << endl; // Insert a¢ter pos 3 22 string msg: 21 sgl = mss // copy 22 cout ce msgt 25 getLine(cin, msg); // read a Line of input 25 cout ccnsp ce ans 7 Example 2: «1000 7.4 Exercises «F009, 8. Formatting Input/Output using IO Manipulators (Header ) ‘The cionanip> header provides so-ale VO manipulators for formating input and out set(int fleLd-widnt: st the flld width fr the nest 1 operation set) is on-stily ane must be issued prot to each 10 operation. The eld width is eset othe deft afer each operation (vith just enough width to scommedst the fl, set4ill (char fiLL-char: st the filed character for pang othe ta with ete] eightinternaisset the abgnment ‘Fixed/setent ste or leting- point numbers) use faed-point notation eg, 12.3) or scenic notation (eg, 128e+006) setprecision( nt nunectaalDtgtts) (or Nosng-poit numbers) spec the numberof digs after the deinsl point boolalpha/robootalpha (er bolt cispay bool values as alphabetic string true/false) or 1/0. 8.1 Output Formatting Example 1 /* Test Formatting Output (TestFormatcedoutput.cpp) */ 2 include 3. include clonanip> —// hooded to 40 formatted 1/0 4 Using manespace Stas ine maint) ¢ hitps:wwn3.ntu edu.sgihomelehchualprogrammingleppicpt_Basics.html 26104 21282020 (C+# Basies - C++ Programming Tutorial 711 Floating point nunbers 3 cout cc Fixed << setprecision(a); // xed format with 4 decinal places 18 cout ce ph ce ond ML cout ce "ft ce seta(8) Ce pl ce “IY ce setu(a0) ce ph ce "I" <é endl; 2 7) setu() 4s not sticky, only apply to the next operation 3B cout ce setesnC=")3 Aa cout ce "I ce setu(S) ce pl ce IY ce setw(a9) ce ph ce "I" <é endl; 15 cout ce scientific; // sn scientific format with exponent 1G cut ce pt ee endl? 1/7 booleans 19 bool done = false: 28 cout ce done << endl; // print 8 (for false) on 1 (for true) 21 cout ce boolalphas”// print true or false 22 cout £& done ce end; 23 return 63 % 8.2 Input Formatting Example 1 /* Test Formatting Input (TestFornattedtaput.cpp) */ 2 include 3) rinelude 4 wineloge 5 Using namespace sta ? fine main ( string areaCode, phoneCodes string instrs HL cout << "Enter your phone nunber dn this format (xxx)aocemaa 1 "5 12 Gingrore0)s// skip "( 33 cin 93 setu(3) 99 areatodes 14 cingrore();// skip") 15 in 9> setu(3) >> phanecoees 35 chnsignore();—//'skap 1 cin > setw(4) >> anstrs 28 cout ¢¢ “Phone nutber Ss (" <¢ arencode < a phonecode-subste(@, 2) co" 2 € phonecode.substr(3, 4) << endl; 23 return os a) 8.3 Exercises «T0200 9. Arrays 9.1 Array Declaration and Usage Suppose that you want o find he average ofthe mats for 3 cas of 30 student, you certainly do net want to create 30 variables ark, mark? Instead, You coul sea single varbl, alle an ary, wth 30 element. Dm ary i lt of eements of the same type, denied by spar of square brackets [To use an aray, you nee to declore the ana wth 3 things name ‘ype and a dmension (or sie or eng) The syntax ie ‘ye orraytoneLorroy.ength};//atvaylength can be 2 Literal or 2 vasiable recommend using» plural name for ray, marks, ros, numbers Fr example, nt marks[SJs___// aclare an int array calded narks with 5 elenants fuble ronbers{10};// Declare an double array of 10 elements font tenos(SI2E}3 (Use cout size, ‘lost values[stze]s Take note hatin Co, the val ofthe laments are undefined after declaration ou can aso inate the array during declaration with comma-separated Ist of values, 5 follows sine numbers(3] = 1, 33, 44): “ hitps:iwwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 2riaa 2128/2020 (C+# Basies - C++ Programming Tutorial ant members] = (1, 33, 445 ine rumbers(5) = (11, 33, 44); // Revaining elenents are zero. Confusing! Don't do ths fmt mamberst2) = G1, 33, 44)) (1 EHHOR! too many inittalizens 11 se (8) 9° () to snstialize alt elements 9 @ ‘ne mombers[S] = (0); 1 First slonere to 8) the rest abso to 9 fant mombers[s] ©} Al) lenent to 9 fos /* Test local array initialization (Testrrayinit.cpp) */ Using nanespace sta; ant const SIZE = 53 tot a(S12t); // uninstiolizes a Sint maing) 3 for (Ane 4 = 85 4 ¢ S126; vot) cout ce ants] 85 sares[2] = 775 sares[3] = 65 sarkel4] = 85 our ce narke[8] ce ens out ce wanke[3] ¢ naris( 4] enels ArrayName:a Array Length: n Index 0 12 na Elements: afo] aft] a[2]a[3} «.« a{n-a} t t First Eloment Last Element To crete aay, you need to known the length for sz) ofthe aay in adware, and allocate accordingly. Once an ary is created, ts length i ued cannot be changed, At times it shard to ascertain the length of an aay (2g, how many students ina css Nonetheless, you need to estimate the length and sllcate an upper bound Thi probably the msjor drawback of wing an aay C++ hata veetor template dbs (ane Cr+11 added an array template css, which supports mami resizable ray ‘ou can ind the sry length using expression sizeof anraytane)/stze0"arraytae[]), where sizeof arrayhone) returns the ttl bytes of he array and sizeof (arrayNae[8]) returns the byes of fist clement (IC does not perform aay inde bound check other wor fhe index i beyond the 3739's bounds, st doesnot iste 9 wamingfrror. For example, Gxt mumbers(stze]? // arsey tnd fron @ 80 6 anbers[a8) = 93, faut a 5 include ‘ using nanespace std 38 tne main) { n 43, 58 68, 90, 68, 78); 13 tne sonsg = 8 14 couble naan, stabev; 45 for (Unt d= 0; 4 < SEZE; s44) { 16 sine mares[i D sang 42 marks[]onarks [4]; aw) 18 ean = (ouble)sun/StZE; 22 Cout ce Fixed ce “Mean is * <¢ setprectsion(2) < mean << endl; 22 —stabev « sqrt((doubte)sunsa/SIZE ~ neantmean); 23 cout cc Hned ce "Std dev de" <¢ setprecteion(2) ¢¢ st@Dev <é endl; Exercises ‘7000 9.3. Range-based for loop (C+ +11) C11 introces 3 range-based for loop fr fr-ech loop to iterate truan ara, a ilsrated inthe following example: 1 / Testing For-each Loop (TestFor€sen.cop) */ 3 Using nanespace stds Sint maing) ¢ 6 "Ane wanberst] = (225 225 33, 44, 5595 11 For each nenber called sunber of array nubers ~ read only 5 for Cine number + monbers) ( no) " 2 33/1 To modity netbers, need to use reference (8) 14 for Gane Snunder + numbers) { % wer = 995 > D 18 for (int number = nunbers) 2 cout To compile the program under GNU GCC (g+¥), you may nee to specty option -std=c+¥0x oF -st ss sstdecouOe -0 TestForeach.exe TestFortach. cop bls setdecostt -o TestForeach.exe TestFortach. cop 9.4 Multi-Dimensional Array For example, sne(21031 = C1, 22, 29, (at, 98, 66) 35 hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html oie 21282020 (C+# Basies - C++ Programming Tutorial Column 0 Column 1 Column 2 Column 3 Row 0 afo]{e] afo}i2] afo]] a[9]13] Row 1 af1]{@] af1]{1] alg] aft}3]_ Row Column Index Index For 2D array table the Fst ndexis the row number, second index the column number. The elements af stored ina so-called row-mjor manner, where the cola nd ne ot fi Example 1 /* Test matti-dinenstonal Array (Test204eray.c9p) */ Using nanespace std oie: printareay(const Snt{ {3}, 498)s Amt myACrayLILI} = (08 2 by (y By 2B05 Mf 299 snitiatszed 7/ Only the faret index can be onitted and Laplied prinvarraytayaray, 295 n> " & ine maing) ¢ 5 43 // Print the contents of rous-by-3 array (colunns Ss fixed) 14 vole printarray(const int arrayt][3]» int rows) ¢ as for Cine t= 03 4 rows #41) { 6 for (int 2 05 4 <3; Hy) £ ” cout < arrayEt]EH] ce" "5 a } 3 out « ends x > 9.5 Array of Characters - C-St 9 Inc. a sving is a char ara terminated by a NULL character *\@" (ACI code of Hex). Cr provides 2 naw string cass under header . The orginal sting in is wn as C-ing (or tye Sing oF Character Sting. You could allocate aCstrng Via: chor sessagel256]; Declare # char areay 11 Can hold a Ctrdng of up to 285 characters terminated by “Ve char sted[] = "Wether; /! Declare ane initiatise with a satring Hiteral™ 11 The length of array is nanber of characters + i (for “e") nar strtehart} = (Wye; "Ty", "a, "\@'}2/) Sane a6 above ‘har stea[256) = “Mellor; 17 Length OF array #0 256, keeping a anaer string. For novices, void Cstng, Use C++ string in header estrings) dscussed eal, Example ‘ou ean ue etn and cout to handle Cstings = chen ce reads ating dented by whitespace s cin.getline(vor, s{z0) reads 9 sting of int vor til noutine of length up to size-2, daring the newne (replaced by “\O") The size typically omesponds to the length ofthe Csring ary. = cin.get(var, size) reads a sving til enn, but eves the newline inthe insu ule = cin.get(), without argument reads the now character U* Test Costeing (Testesteing.crP) */ include Using nanespace stds char msg[256]; // Wold a string of up to 255 characters (terminated by "\8") cout c "enter a message (with space)" ¢¢ endl; 3 5 tne maing) { a 3 ensgetline(nsg, 256); // Read up to 255 characters nto aig ae cout cc weg ce andl; n 12/7 Access via null-terminated character anray 13 for Gant > 8; msgi] Im '8ts 4H) a cout ce maals 3%) 15 cour «¢ endl; 18 cout ce "Enter a wand (without space)" <¢ end 3B cin >> mses 22 cout case ce end; hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html s0iaa 21282020 (C+# Basies - C++ Programming Tutorial a 2217 Access via nul1-terminated character array 23 for (int 1 = 8; asgli] I= "0's 44) ¢ 24 cout ce meals BY 25 cour «¢ endl; 9.6 Exercises \roD0) 10. Functions 10.1. Why Funct ‘times, certain portion of codes has tobe use many times Instead af e-ting the codes many times, is better to put them into “subroutine, an “el ‘his ‘subroutine’ many tne for ease of mintanance and understanding. Subroutines called method Java or function fn C/C* ‘The bent of wing aneton te: 1. Divide and conquer: constuctthe program rom smle smal paces ar componenss Madularize the program ita Sel-contaned tasks. 2 Avoid epeating codes tis eas o copy and pase, but had to maintain and synchronize a the copies. 5. Software Reuse: you can reuse the funcons in ther prograns, by packaging them ino bay codes. ‘wo partes ae involved in using a function: a caller who cls the function, and the futon cafed The clr passes arguments) tothe function The function receives thse arguments, performs the programmed operation within te function's boy, ana reams a plee of suk back 9 the cle 10.2 Using Functions Get Started with an Example Suppose that we need te evaluate the area ofa cla many times tis beter to it a function called getAnea() and te-se't when needed Caller —main() double radius = 1 Function ~ getarea() double area; area = getArea(redius); Arguments} double getarea(double r) { return r* © * 3,14159265; cout 3 Using narespace stds 6 11 Function Prototype (Funetion Declaration) 7 double getArea(doubie radius) 3 ine maint) { te" ouble radtust = 2.1, aneat, anea2: Uff call function gethrea0) 42 areal = getarea(radiusi); 13 cout ce Yarea 135 * 1 The parometerist consists of comma-separated porametetype and porametername, ie, poraN-1-type paraw-I-nane, paron-2-type paran2- 1 The eturaVoluetype specifies the type of the retum vale, such as int or double, An sped ‘elu ype called vosd can be used to denote thatthe function tums no value In C++, function i llowe to flu one vale of no value od R eant return multiple values. (C++ does not allow you to raturn an ray The “return” Statement Inside he functions body, you could use a return statement to return aval ofthe returnValueType declared in the function's heada and pas the conta back to the calle. The syntai Take note that invoking a function (by the calle tanses the contol to the funcion The return statement inthe function wansers the contrl back tothe cal Function Naming Convention | function's name shal be a vtb or vero phrase action), comprising ane or more words. The Fist word isin lowercase, whe the rest are inta-capialzed (koown as camel cos For example getareat), setRadius(), novedown(),LsPrine(), ee Function Prototype In Ces, function must be declared before itcan be called, can be achieved by eter placing the function dfntion befor it being used, or declare a 0 led faretion protoyre | functon protorype el he compl he functions interface Le, the retum-type, function name, and the parameter type Ist the number and eype of praraters, The function can now be defined anyuhere in the fle Fer example, foubte getareaccoubley; / without the parameter nave Ext maxtint, 190, ‘ou could optional include the parameter names in the fonction prototype, The names wll be ignored by the compiles, but sere as documentation. For example, lube getarenCcovble radius); // poraneter nanes are ignored, but serve os dociment Ent mae(int manent, £08 uated) Function prototypes are usualy grouped together and placed in 2 socalled header fle. The header file can be inclided in many programs We wil discuss header fle later, Another Example We nave a function called ax(int, dnt), which takes to Sn an tum their maxim We invoke the max) function from the maa). [+ Testing max function (TestiaxFunetion. <9) include Using nanespace stds ne maint) { cout c¢ naxinun(S, 8) <€ endl; // Call naxinun() with 2iteras a 5 tne macimun(int, Ant); // Function prototype (declaration) 6 5 1 c= axinun(s, Bs 11 Call waxinun() with vardables 2 cout eee ce ends 14 cout ce waetnun(c, 99) e endl; // Call moxinun() wo 11 Function definition 48/7. fonction that returns the naxime of two given int 15 ine naximum(in mura, ant rund) ¢ 22 "return (aunt > muk2) umd mes The “void” Return Type ‘Suppose that you need a function to perform certas action fg. printing without a nee to atu aval to the clr, you an dedle is etum-alue ype as ‘void nthe fancson’s body, you cou urea “retunns” statement without 3 retum sake to return control to the cle I hi cao, the return statement i hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html aia 21282020 (C+# Basies - C++ Programming Tutorial contions. there isno return statement the entire body wil be executed and control retuns tthe caller a he and ofthe body ‘Actual Parameters vs, Formal Parameters Racal thts function racsves arguments rom caller, performs the actions dafned nthe functions body, nd return value (or nothing) othe calle, In the above example the variable (@ouble radius) declared inthe signature of getArea(double radius) is know as formal parameters scope is within the function's body When the functions invoke by cal, the caller must supoly so-called actual pramers (or argument, whose vale i then used forthe erea(radsust), radius ithe atul parameter, ith 9 value of 12, cual computation Fer exam when the Sanctions inoked via “area} = Scope of Function’s Local Variables and Parameters ‘Al vatiales, including function’ parameters, declared inside a function are avaiable only to the function. Thy ae create when the function scala, and feed {dostrayed after te function retuns. They ao cal oct voriabes because they are la othe function and not avaoble outside the function. They are abo Caled automatic ails, because they ate crested and destoyed automatilly- no programe’ expt action needed to allocate and deals them. olean Functions [A boolen function retusa bool vale fof ther tru or false) tothe calle ‘Suppose that we wish to wrt afuncton called 1s044() to check fa given aumberis odd * test soolean fanction (BooLeanfunetionTest. Using nanespace stds bool {s04a¢ ine); 38 ine main ( 41 egut <¢ boolalpha; _// print bool as true or False 12 cout ee 504405) Ce end; // true 1B cout ce isos) ce ently /7 Fase Ma cout ce Ls00d(-5) eerendl // Fase 3) 6 17 bool ts04acint munber) ¢ ae $F (umber £2 == 3) ( melee a return false; ‘This seemingly comect codes produces false for = because -S42 is 2 instead of 1. You may rewrite the contin bool $s064Cins onber) ( 4¢ (ronbor X2 == 8) { recuen false pelse ( ; 7 ? The above code produces he coract answer, buts poor For boolean function, you should simply return the resultant boo} vale ofthe comparison instead of ing a conditional statement as flow book Seeven(sne numer) { return (numer % 2 %: > ook Ss04d(Ant unter) { return I(rumser X 2 > 8)5 11 08 return teseven(nber) st main() ¢ AF (isfven(nunber)) (——// bon"t wr > (estvan(nurver) == te) > 10.3 Default Arguments (C+ introduces so-called default arguments for functions. These defau alas would be used ifthe calle ont the coesponding actual rgumntncaling the ‘uncvon, Default siuments ae spect inthe function protetype, and cannot be repeated inthe function ceftion The dtu arguments ae retbed bared ‘onthe posions. Hence, they can onl be used to substitute the tang arguments o avoid ambigty, Fr example, 1 /* Test Function defautt angenents (functionbefaultargunent.cpP) */ Using nanespace stds 5/1 Function prototype - specify the default argunents here 6 ine fomitine = 1, Int = 2y ant = 3) hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html sia 21282020 (C+# Basies - C++ Programming Tutorial toe fonacine, ants Ant = 35 3 ane main() 2 20 cout ce FantCes 54 6) << endls // No default Me cout ce Fun, 5) ce endl // 4, 5, 3deraull) 12 cout &e Fame) << endl; // Ay 2{defaule), default) 33 out ce Fut) : ‘ou should specify the deat arguments the function prototype (section). They can only be defines once fons-dfition rl), and cannot be repeated in the fineion dein, Default argument is not absolutely necessary. The codes could be hard to mainan 10.4 Function Overloading (C++ ineduces function overioasing (ot function polymorphism which means many forms, which afows you te have multiple vetsions ofthe same funcson name, diferentes by the parameter Ist (number, ype or order of parameters, The version matches the ale’ argument it willbe elected for execution. For exam ‘include Using namespace stds 1 (FunctLonoverloading.cpp) */ void fon(aouble, int); 11 Version 2 3 S vols funtint, int, ant); // version 2 7 ois fun(int, double): 11 version 3 a soe maine) re fun, 2, 393 // version > M1 fun(tie, 2); 7 version 2 az Fant, 2.8); // version 3 13 fun(La, 2, 395 // version 2 ~ govble 1.1 casted to ant 2 (withovt warning) 1 FQ, 23, 05 16 11 error! no matching function for call to “fun(int, tnt, int, Int) yi ft, 2); 18 17 eeor! cal of overtosded ‘fun(in, ant)’ s= anbguous ° 11 vote: candidates are: 2 11 veld tun(doubie, 00 a 1 eid fanart, sovble) 22 1/ #na.e, 2.0); 2 17 error: call of overtosced ‘fun(dovble, double)’ 4s anbiguous wy 25 vole fun(int mt, ant m2, ant m3) { // version 1 27” cout ee "version 2” Ce endl; 2» 30 vola fun(double na, snt m2) { // version 2 31 cout ¢e "Version 2° Using nanespace stds 2 S11 Function prototype 6 ink sun(int array[], ant size); // Need to pass the array size coo 2 vote prine(ine array{], Smt si20)s 11 test Driver re ine ming a" ine alf) = (8, 4 5, 3, 235 12 prine(ady 5950 1/ (84051542) Ba Coat ce Naum Gs ~ ce suM(a2, 8) ce andy // sun 45 22 uw) 6 16/1 Tunetion detinition 17) Retorn the sun of the piven array 48 ine sum(int arrayL}, int size) { ao" tne sun = 8; 28 for (int 1 = 05 1 ¢ sizes ant) ( a sun t= arrayli}s 2) 23 return sums 2a} 26/1 Print the contents of the given array 27 vote print int array[], Ant size) { ae cour ces 23 for (int 125 5.6 size; et) { xe cout ce aryl} x fee siee = 0 ( 8 > : Mo) 35 cout ce "Pe endl; oD 10.6 Pass-by-Value vs. Pass-by-Reference ‘There ae two ways that a parameter an be pased into a functon: pass by wee vs. pass by eernce Pass-by-Value In pss-byalue “copy of argument crested and paced into the function The invoked function works onthe “cane and canna madly the eign copy In cic, fonamantal ype such a8 Smt andl double) are pased by value That is you cannot modi elle al inside the function =thare eno side effect. Example (Fundamental Types are Passed by Value) 1 /* Fundonental types are passed by value into Function (Tes ‘include clostrean> Using namespace Stas sseyalue.cpp) *) S11 Function prototypes © ine tnctine number); 7 11 Test oriver ine ming) AL cout << "Before calLing function, a 1s * cen cc endls // 8 32 ine result = Sne(n)s 13 cout ce "Attar calling function, a is" cen ce endls // 8 14 cout ce Mrasult as” ce result €e endl; "9 wD hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 35104 21282020 (C+# Basies - C++ Programming Tutorial 19° Ane dretint manber) { 20" senunber;// Wodify parancter, 10 effect to ealter ny . Pass-by-Reference (on the other hand in pas-by-rlerence aerence ofthe cles vatiale passed inte the function. other wards, the invoked functlon works onthe same ara. the invokes function modifies he parameter the same all's copy wil be modified aswell In. C/G+ +, arrays ar passed by reference, That is you can modify the content of the eal’ tay inde the invoked faneton «there cou be defect in passing arays ino functor C/C++ does not low functions to retum an ara. Hence, you nish te wrt 3 function that modifies the contents of a aay (e.g, sorting the elements ofan sry, you ned to rly on pss-by-tferance to werk onthe same copy inside and outside the function. Recal that in pas-byvale the invoked function works ‘ona lone copy ant has no way to modiy the origina coy. Example (Array is passed by Reference): Increment Each Element of an ‘include clostream> Using namespace std 3 6 Wold ineCint arrayl], int S26); 7 wots print(int arvayi], ant $126); a 11 Test oriver 1 ine aain() ¢ Mme AID = (8, 4) 55 3 295 13/1 Before increrent 3a prinetaty 5); 1 (8,4,5,3,2) 13/7 bo Ancrenent 36 ne(at, 595 // Aeray Ss passed by reference (having side effect) a7) Rete Increment 18 prine(at, 55 // (945161443) 2111 Function definitions 23/1 tncremant each alenent of the given array 24 vole incCint arrayl], int size) { // arrayt] 1s not const 25" for (int 4-8; 1'¢ size; ext) { 8 arraylilies // side-erFect > 3 30 // Print the contents of the given array BL vote print(int arrayl], ant size) ( Br cout ces B For (int 5 0; 4. size; ot) { x» cout ce arrayl i]s % Wee size = 3) ¢ eo Dray i passed int Kncion by reference, That is, the ioe function works on the same copy ofthe stay a the caller, Hence, changes of aty inside the ‘uncton reflected outside he function (e, side effet, Why Arrays are Pass-by-Reference? ‘rays esignes tobe pase referenc, instead of by value wsng a cloned copy. This is because pasing huge ary by values inefcient- the huge array etd tobe cloned 10.7 const Function Parameters Pas-by-eferance rite corrupting the orginal data. f you do not have the intention of madiying the arrays ide the funtion you could use the const Keyword inthe fection parameter, A const function argument cannot be modified inside the funtion, Use const whanever posible for passing references a8 preven ou from inseverenty modifying he parameters and protects you against many programming Example: Search an Array using Linear Search In a near search, the search key is compare with each element ofthe aray inary. If there is 2 mate, it returns the index ofthe aray between (0, sie thers, itetums-1 or the sie of of the ary (some implementations des with only petve indexed) Une search as complet of Of 1 /* Searen an array for the glven key using Linear Search (LinearSeareh.cpp) */ 2 include hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 36104 21282020 (C+# Basies - C++ Programming Tutorial 3 using narespace stds 5 int Linearsearch(const int af], Ant size, int key); 6 7 int main() { 8 const Sot SIZE = 9 int aN{SIZE) = (8, 4, 5, 3, 2, 8, 4, 5 11 cout <¢ Vinearsearch(at, SIZE, 8) << endl; // @ 12 cout €e Linearseaneh(a4, SIZE) 4) €e endl // 1 13 cout & Hinearsearch(at, SIZE, 99) << endl; // 8 (not found) “od 16 _// Searen the array for the given key 18 Ant LinearSearch(const int af], int size, int key) ¢ 19" for Cine i = 85 1 < size; #1) { 2 SF LL] == key) return fs a) Program Notes += 10001 Example: Sorting an Array using Bubble Sort Wiki "Bubbi Son forthe detailed algorthm snd ilsration. bret we pass thes the it, compace two adjacent tems an scp them they aren she wrong order, Rapetthe pas unt no swap ae needed, For ex, (0,6,5,3.2.9,402) 3,2,9,4.2) 3121914133 ee) 234,405, 23.8.2,65, 23 1h 2.9,5,4085,8,9) -> (2,1,3446,5,8,9) 20103 08,8 5.859) => (a 20308,8,5,8,9) 11,20308,8,5,8,9) Bubble sorts nt ecient, with complet of Of 1 /* Sorting an array using Bubble Sort (Bubblesort. Using nanespace stds 3 5 void bubblesort(int af], int size); 6 void print¢const Ant af], int size); fine maing) { const int SIZE = 83 ae int al) = 65,3, 2, 9, 4 tbs n 12 prineta, size); 1B tout ce endl; 14 bubblesort(a, size); 35 printta, 812; 18 cout ce ends 15. // Sore she given array of size 28 vols bubolesort(int af], int size) { 21" bool done = false; // terminate Lf no wore swap thru 2 pase 22 Int pass = 8; // pass number, for tracing 23 ine tana 11 Use for saapping 25 white (done) ¢ hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html s7iaa 21282020 (C+# Basies - C++ Programming Tutorial 2% cout Ge "PASS * ce Hepass ce" vss" 6 ens // for tracing 2 77 Pass theu the List, conpare adjacent itens and swap cs U1 em $f they aren wrone order x for (ine t= 0; L¢ size = 4; 441) a 4 GE) > ateay) ( » print(a, size); // for tracing 2 feo = alls M aU] = alset}s % Lisa] = temp: Gone = false? // swap detected, one rore pass cout ce "=> "5 // for tracing peiat(a, size); cout << endl; 11 fring the contents of the given anray of size ole print(canst dnt a], Ane size) { cout «<5 for (iat 120; 5 tzes 448) ¢ cout < alsls HF (1 size’ 2) cout «5 cout ce") Program Notes + {1000} Example: Sorting an Array using Insertion Sort Wi “iseton Sort” or he algorithm andilsratin In bi, pass tra the Ist Fr each element compare with al previous elements and inset it at the corect, postion by siting the other elements For example, 80815,3,2:96402) Df 5.5.2.5¢6.) ‘Si3.2.86.2) 5.8) G29) 185.8) (2.8.4.2) (a3assia) Gea) (asia) tea) salsa) 12.3,4,455.8.9) Insertion sot ao not fic, th comply of On. 1% Sorting an array using Insertion Sort (InsertionSort.cpp) */ ‘include clostream> Using nanespace stds old print(const int a], dnt ihin, int ix); foe ming) 3 5 void insersionsort(int aff, int size); a ne tne [SIZE] = (8, 4 5, 3 24 9, 4 15 u 32 printta, @, size - 2)5 12 cove ce ends 44 Insertlonsort(a, S126); 35 print(a, 8, Size - 2); 16 cout ce ends vo 38/1 Sore the given array of size using insertion sort 28 Wot Ansertionsort(int al], Ant size) { 21” Ane temp; // for shifting ele 22 for (int 4 = 4; 4c size; evi) { 2 11 Fon tracing 24 print(a, @, 1-3; // atready sorted 3 print(a, 4; size - 1); // to be sorcea 28 out << ends 2 11 For elenent at ‘per position sn (@, 1-1 » U1 wien is arena sorses xe 11 Shift-down the other elenents a ‘for (int prev = 0; prev <1; Horev) ¢ 2 iF (ati « alprev)) { a 11 insert a[s] at prev, shift the elements dow ¥ ‘en = af: 35 for (int shift = i shift > prev —shieey ( 3 afshift] = a[shist-1]; ” ) hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 38104 21282020 (C+# Basies - C++ Programming Tutorial » atprev] = temps © » a ) a 11 brine the contents of the array in (AR, sax} void print(const int a[], int ihn, int HRax) ¢ cout ces for (int 4 thin; ce amas #44) cout ce af315, 11 < IMax) cout ce") ? cout ce} Program Notes + ToDo} Example: Sorting an Array using Selection Sort Wiki Selection Sor” forthe algorithm nd ustration. nb 1 Solel the sles element nd swap with the hea of hes. For examol, £806,5,3.2.9,462) Debby © 0 (ues) 11) (4,5,5.2.5,6,8) 5 G1) 215,3,609,6,8) (1.2) (513.4.9,4,8) > (22) ,5.4.9,0.8) ina) asta) > Gl2a) esses? 1112.3,8) (5,954.8) > (12.3.6) (6.9.5.8) €112,3,4,4) {9)5:8) > (203,88) 15,9.8) ia3ites) (a) > Oo23,66,8) 18.9) 1122,314445,8,9) Selection sr i algo nat efficent with complenity of tn, 1. /* Sorting an array using Select Using nanespace stds on Sort (Selectfonsort.cpp) */ 5 vold selectionsort(int af], tnt size); 6 vols print¢const ant a[]s int akin, int Max); 5 ne maing) { const int SIZe ae ine afSIze] = 8, 4, 5, 3, 2,9, 4, 12 print(a, @ SHE - 1)5 a3 aut ee endl; 14 Selectionsort(a, size); 35 —print(a, 8, Size - 2); a5 cout ce endl; vy 15/7 sore the given array of size using selection sort 28 vole selectionsort(int al], int 3iz0) { 2a ne tempi 1/ #0 swaping 22 for (int d= 0; Fe size - 45 41) ¢ 2 11 far tracing 2 print(a, @, 3-0 2% print(ay 1, size - 1)5 2 11 {@, 4-1} already sort 2 11 Search for the smallest element in [i, size-4] 2 1) and suap with af] xe {ne mintndex = 43. // sssune Fist elorent is the snatiest n for (ine j= bas je sizes 49) 2 44 (a(3] « alnintndex)) minkndex = 33 2 } 3 4 (etntndex t= 4) (17 sup 5 eng > aft} % AUD) = aleintndexd: ” afwintndex) = temp: a ? a cout ce" 2 peiat(a, @ 4: 3 print(a, 4 size - 135 %® a 448 // print she contents of the array in (Ania, shox] 43 vole print{const int al], ine thin, ine HN) ¢ se cout cet hitps:iwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html 01a 21282020 (C+# Basies - C++ Programming Tutorial 51 for ine 4 = shins $e as HH) 3 cout ce alt]; 33 AE (Le ax) cout ce) se) 53 cout ce") ss} Program Notes + 17000) “const” Fundamental-Type Function Parameters? ‘ou could ako use const for fundamental-ype function parameters [such as int, double} to prevent the parameters fom being modifi nse the function. Howeve, as fundamental-ype parsmetes are passed by value (vith cloned copy) there wl never be side effect onthe calle. We typically do net use the const Keyword for fundamental types. nother words, consti wad inccate tha thee shall NOT be ede. 10.8 Pass-by-Reference via “Reference” Parameters [As mentioned, parameters of fundamental ype sue a int double) are pasnc-oy-aiue. Thats» clone copy isused inside the function Change to the lone copy isi the function has no side-efft othe calles copy. "Nonetheless you cn pass 3 fendamentl type parameter by reference vis the s-cale reference pormeter denoted by & For exam 1 /* Test Pass-by-roterence for furdanenta via reference declaration (TestPassayterarence-cPP) */ ‘include clostream> Using namespace std 6 tne squaresyWatue (int number); 7 vole squaredyRererence (int # number); // Passoay-reference ne main cout << *aafore call, value ts " ¢¢ m1 ce ends // # 12 cout €e squaresyaluc(nt) ¢€ endl; // 99 side-effect 33 cout ce "After call, value is" <6 ml ce-endly 1/8 1a 16 cout ce "Before call, valve ts " ce n2 cc endl // 9 37 SquaretyReference(na}s. // side-effect 18 cout ce "Aten call, value is" ccm? ce endl; // 81 w ) 211 pass parameter by value - 0 side e 22 Ine sqvaresyalue (int nunber) { a) 2s 26/1 pase paranater by reference by declaring as reference (8) 27 ji. = wish side effect to the caller 2h Wold squaretyReterence (int & number) { 29 uber = sunber * numbers In function squarebyererence(), me declare the parameter runber is passed by reference by declaring its ype ab int & erence of Int. otis way the callers copys ures insise the function Gnstesd of clone copy in pa-byaue), Changes inside the function has sdeetet Pascby-teference i NOT commonly used or fundamental pes (ch 38 Int, double} ~ the above example is purely meant for academe station But i ied extensively for compound types (such 38 trays an objects to avoid cloning huge dts for beter performance, We shall revs pass-by-zference in ‘object-oriented Programming (007) chapters. 10.9 Mathematical Functions (Header ) (C++ provides many comman-used Mathematical functions in Ibray cenath> (ported over om Cs math.) Te signatures of some ofthese functions are SiG)» €050Ds tan), a65N(H), a€0s(x), stan) Take argunent-type and returh-type of fleat, double, Zong double. atanayy, 9) Return are-tan of y/x. Better than atan(s) for handing 98 degree. sinn(, €9sh(x), tann(n) hyper-trigonowetrie functions pox, Ye sart(nd: over and square root c2il(0, floors): returns the ceiling and floor érteger of Floating point nunber. fabs, fedex, y): ‘losting-poine absolute and nodules ©3900)» Yog(0), 2o9i8¢=) exponent and Logaritie functions, hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html oiaa 21282020 (C+# Basies - C++ Programming Tutorial 10.10 Generating Random Numbers The cstalib header (ported from Cs stelib.¥) provides a faction rand), which generates a pseudo~andom integral number between © and RAND AK Uinelsve) #aN0_MHx is» constant dined in est 414 Eypialy the maximum value of 16-82-bit signed integer, such a6 32767, You cn generate 3 random number between (@,) va rand() Xn ‘and() generates the sme squence of pseudo-random numbers on stferentnvecaons. The cetblib also provides» srand() funtion to sed or ini the random aumber generator We typically seed it wth the crret time obtained via tine(2) function fo heade, which etuns the number af seconds January 18,1970 Example 1: Test rand() and srand(tine(e)) 1% Test fandom Nunder Generation (Testand include ‘include // for rand(), stan) include cetine> // for tine() Using nanespace stds, ft mang) { 11 rand) generate 3 candon nuwber in [8, RARD_PAK] out ce "RAND MAK 8 "ee RDYOX €& erly 7/3267 11 without seeding the generator 17 You will get the sane Sequence, every tine you run this progran for (iat 1285 5 38; #94) { cout ce Fand() £208 <<"; // weed cestale> header ? cout c< endl 11 Seed she candon nurber generator with current tine Srang(eine(@));// need and header 11 You will got-aitferent sequence on different run, 11 because the current tine 1s aisrerent for (int d= 0; 3 € 38; #44) { cout ce rand() K 308 << * "5/1 need cesta b> header > out << ends } Example 2: Test rand()"s Distribution We shaltest the rand()’s stibution by repeatedly throwing a 6-sided die and count the occumences 2 5 a 8 a 1% Test rand() distribution by throwing a die repeatedly (Tes ‘include ‘include // for rand(), srandt) ‘include cet ine // for *n0() Using manespace sta; edenDie-cep) */ const int TOTAL COUNT = 20000085. // Close £0 TNT_NAx const Ant NU_FACES = 6; nt frequencies(6] = (8)s // freauenctes of @ to 5, anit to zero ne mating) { srandltine(@)); // seed randon nunber generator with current time 11 Throw the die and court the #requeneies for (int 4 = 6; 3 TOTAL CONT; 111) ¢ sefrequencies[sand() ¥6]5 > 11 Prine statistics cout ce Fixed ce setprectston(2); for (int i= 05 3 MMLFACES $40) { cout << Lod ce "2" ce frequencies[ 4) £7 (£6 100.0 * frequenciesT] / TOTAL COUNT ¢¢ °R)" €& ends ? panes 6.668) pn (6.66) san (6.660) 388 (6.68) see (6.68) gues (6.670) [As seen fom the output rand() i fly uniformly dstribted over (8, RAND_MAX) 10.11 Exercises ‘70001 hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html aaa 21282020 (C+# Basies - C++ Programming Tutorial 11. File Input/Output (Header ) The cfstrean> header provides fstrean inp file steam) and ofstrean (out Ae sream) fr fleinput and output. The steps fr le inputourp ate 1. Create i¢strean fr input or ofstrean for output 2 Connect the tenn to an input or output fle ia open FeLenane) 5. Perform formate output via stream insertion operator | // ‘Sle stream G finelede cestatio> 7 using manespace std; a 3 int main) { ae" fstrean fin; // anput strean 11 of stream Fouts // Output stream 13 // Try opening the input file 1a Finvopent"ins txt"); a5 be (Finis epent)) ¢ 6 cere ce Perron: open input file failed” << endl; D abort); // Abnarmaiiy terninate the progran (in ) ~ 8 22 int sum = 0, nunber, count = 0; 21 wnide (1(449.€0009) ( 2 11 Use 99 te read 2 ‘Fin >> nunwer; 24 sn nomen 2%) 27 ouble average = double(sun) / counts 2a cout ce "Count =" <¢ count CC" average = * ¢ average << endl; 2 finelose(): xe 31/1 Try opening the output file 32 Fout.opentTout txt") 33 AF (1¥out.45_open0)) ( » cere << "arvort open output file failed” <¢ endl: 5 seortOs 38 fout > and cfr input and output sin to ein >> and cout «(Advanced note: LFstreae sa subcs of Lstrean, ve «= Siiley 10 manipulators, such a8 fixed, setprectston() and seta(), wor on the fie steams ‘cin belongs ofstraamis a subclass of ostrean where cout belongs) 11.2 Exercises «7000 12, Namespace When you use ferent rary mods, here is slays 9 potenti or name cathes, as diferent brary may use the same name for etferent purposes This problem canbe esohed va the use of namespace in C++. A namespace is» collection for deniers under the same naming scope ts krown as package [UML and Java) The entity name under 9 namespace is qualifed by the namespace name, flowed by :: (known 3s scope resltion operator in the form of ranespace:sentitynane hitps:wwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html a2iaa 21282020 (C+# Basies - C++ Programming Tutorial To place an entity under a namespace, use keyword nanespace 35 lw: i #0 ¢ 1 fanetion class ter ( / eanpourd type such a5 class and struct slnespace::t00 ‘anespace:: 10) ‘pmanespace: bar ‘A ramespace can contain variables, functions rays, and compound types such 35 csses and sretures Namespace Example 1 include 2 3 namespace a { // contains varsables a ens a 5) 4 namespace b {// contains function 3 Mine maxGine mi Ane m2) ¢ 1° return (o> ma)? n8 + 625 Ry 14 int main) ( 35 Natasreout ce assit ce stassenals . M6 -Starveout ce Beeman(assls, aii) ce stassendl; // 9 v > Namespaces ae opaned. i ther words, you can add more namasinto an existing namespace using adtonal nanespace definition, Using Namespace For example, il the identifiers in the C++ standin Eras suena cout nl an string) are placed under the namespace called std To reference 29 ‘enter under a mamespace, you have thee options 1. Use the ul qualified names, such as sta: cout, sta: venl, sta: ssetu() and sta: string For example, stdsteout c¢ stdsiseta(s) ce 1238 «4 stdesendly Missing the "st" ests in ero oo was ot decared in thi scope. 2 Use using decoration to declare the parca denies Fer exams sing sta: scouts sing 504: serdl; ait ce stastger(s) 2236 ce endls You can omit the “std: for cout and endl, but you stl have to use st for sete 3. Use a using namespace avectve For example, ‘sing namespace sts Colt ce seru(s) ce 1284 ce ona; The using eamessace diective effectively brings al he identifies fom the specfed namespace to the global cope asf they are avaiable global You £2 reference them without the scope resolution opel. ake note thatthe using nanespace directive may result in ame cashes with dente inthe sHobal scope. ‘4 For long namespace name you could define a shorthand (or alla to the namespace a allows anespace shorthand = ranespace-nane You ean now ele to your cass as shorthand: ent yam ‘As mentioned, al the standard Ce lary components are packaged isd a namespace called st, They include cin, cout, endl, setw(),setprecision() nd string Hence, we always induded a “using nanespace sts" drectve ater the "tineluge " and “include ” You could so wie the qualifies name such ar sta: :cin, stericout, sta rend, statsstring iste ofthe using directive You coud algo use selective using such a “using stdsrcin;', using std::cout’, "using std: endl;" and ‘using std::string; Compate he following we code samples: nt maint) ¢ ) sat maint) ¢ ting notergace stg; // sts nanespace Ss seatlasle t9 maén() only hitps:iwwn3.ntu edu sgihomelehchualprogrammingleppicpt_Basics.html aaa 2128/2020 (C+# Basies - C++ Programming Tutorial ) Not: you could use the Cote header “Lostrean.h whith ds not use namespace to replace the fat wo ine inthe fe sample ai Inv. an entity arable, function or chs belongs othe glbal namespace (ented by :: with no namespace nar fits nt enclose within 9 namespace eckraton For example nain() canbe ented 35 man). Link to "C++ References and Resources hitps:wwn3.ntu edu.sgihomelehchualprogrammingleppicpt_Basics.html aaa

You might also like